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;
}
相关推荐
yue0085 小时前
C# 更改窗体样式
开发语言·c#
Charles_go7 小时前
C#中级1、元祖和值元组有什么区别
c#
C#程序员一枚10 小时前
导出百万量数据到Excel表
c#·excel
攻城狮CSU12 小时前
C# 异步方法
开发语言·前端·c#
ekkcole12 小时前
java word转pdf工具类,兼容linux和windows服务器
开发语言·pdf·c#
yangshuquan13 小时前
C# 委托和事件的3点区别,你知道几个?
c#·委托·事件·编程技巧
她说彩礼65万18 小时前
C# Lambda 表达式
开发语言·c#
烛阴19 小时前
C#常量(const)与枚举(enum)使用指南
前端·c#
阿Y加油吧20 小时前
java并发编程面试题精讲——day02
java·面试·c#
T.Ree.20 小时前
汇编_mov指令
汇编