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;
}
相关推荐
晨星shine2 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530142 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526742 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526742 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang3 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf6 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530146 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools7 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的8 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21888 天前
.NET 本地Db数据库-技术方案选型
windows·c#