温馨提示×

c语言怎么读取txt文件并输出

小亿
82
2024-04-28 10:47:43
栏目: 编程语言

在C语言中,你可以使用文件操作函数来读取txt文件并输出文件内容。

下面是一个简单的例子:

#include <stdio.h>

int main() {
    FILE *file;
    char ch;

    // 打开txt文件
    file = fopen("file.txt", "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    // 逐个字符读取文件内容并输出
    ch = fgetc(file);
    while (ch != EOF) {
        printf("%c", ch);
        ch = fgetc(file);
    }

    // 关闭文件
    fclose(file);

    return 0;
}

请注意,以上代码中假设文件名为"file.txt",你需要将文件名替换为你要读取的txt文件名称。另外,你也可以根据自己的需求修改代码以满足其他功能。

0