IO的概念和标准IO函数

作业:

1.使用标准IO函数,实现文件的拷贝

复制代码
#include <stdio.h>

int main(int argc, char *argv[]) {
    // 检查是否提供了源文件和目标文件
    if (argc != 3) {
        printf("Usage: %s <source_file> <destination_file>\n", argv[0]);
        return 1;
    }

    // 打开源文件以读取
    FILE *source = fopen(argv[1], "rb");
    if (source == NULL) {
        perror("Error opening source file");
        return 1;
    }

    // 打开目标文件以写入
    FILE *destination = fopen(argv[2], "wb");
    if (destination == NULL) {
        perror("Error opening destination file");
        fclose(source);  // 关闭源文件
        return 1;
    }

    // 逐块读取源文件并写入目标文件
    char buffer[1024];  // 缓冲区用于存储读取的数据
    size_t bytesRead;
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
        fwrite(buffer, 1, bytesRead, destination);  // 写入目标文件
    }

    // 检查读取和写入是否成功
    if (ferror(source)) {
        perror("Error reading from source file");
    }
    if (ferror(destination)) {
        perror("Error writing to destination file");
    }

    // 关闭源文件和目标文件
    fclose(source);
    fclose(destination);

    printf("File copied successfully.\n");

    return 0;
}

2.使用fgets函数,打印一个文件,类似cat

cs 复制代码
#include <stdio.h>

int main(int argc, char *argv[]) {
    // 检查是否传入了文件名参数
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }

    // 打开文件
    FILE *file = fopen(argv[1], "r");
    if (file == NULL) {
        perror("Unable to open file");
        return 1;
    }

    char buffer[1024];  // 用于存储每行读取的内容
    // 逐行读取文件并打印
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("%s", buffer);  // 打印当前行内容
    }

    // 关闭文件
    fclose(file);
    return 0;
}

3.计算文件的行数

cs 复制代码
#include <stdio.h>

int main(int argc, char *argv[]) {
    // 检查是否传入了文件名参数
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }

    // 打开文件
    FILE *file = fopen(argv[1], "r");
    if (file == NULL) {
        perror("Unable to open file");
        return 1;
    }

    char buffer[1024];  // 用于存储每行读取的内容
    int lineCount = 0;  // 用于计数行数

    // 逐行读取文件并计数
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        lineCount++;  // 每读取一行,行数加1
    }

    // 打印文件的行数
    printf("The file has %d lines.\n", lineCount);

    // 关闭文件
    fclose(file);
    return 0;
}
相关推荐
cimeo3 小时前
【C 学习】06-算法&程序设计举例
c#
百锦再4 小时前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
WYH28714 小时前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#
hqwest15 小时前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
做一位快乐的码农19 小时前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
DavieLau19 小时前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#
张人玉19 小时前
C#Encoding
开发语言·c#
hqwest21 小时前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
小码编匠1 天前
C# Bitmap 类在工控实时图像处理中的高效应用与避坑
后端·c#·.net
small_wh1te_coder1 天前
GCC深度剖析:从编译原理到嵌入式底层实战
汇编·c++·面试·嵌入式·状态模式·c