新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c语言怎么读取当前目录的txt文件,C语言怎么读取字符串

发布时间:2024-03-19 17:15:34

c语言怎样读取当前目录的txt文件

要读取当前目录中的txt文件,您可使用以下代码示例来实现:

#include <stdio.h>

int main() {
    FILE *file;
    char filename[100];
    char line[100];

    // 获得当前目录下txt文件的文件名
    printf("Enter the name of the txt file in the current directory: ");
    scanf("%s", filename);

    // 打开文件
    file = fopen(filename, "r");

    // 检查文件是否是成功打开
    if (file == NULL) {
        printf("Error opening file.
");
        return 1;
    }

    // 读取文件内容并输出到控制台
    while(fgets(line, sizeof(line), file)) {
        printf("%s", line);
    }

    // 关闭文件
    fclose(file);

    return 0;
}

在这个示例中,用户需要输入要读取的txt文件的文件名,然后程序会打开该文件并逐行读取文件内容并输出到控制台。最后,程序会关闭文件。请注意,这里假定txt文件在当前目录下。您也能够根据需要修改代码以适应区分的文件路径。