【问题标题】:How to read and print the contents of a txt file in C如何在C中读取和打印txt文件的内容
【发布时间】:2019-10-23 21:22:27
【问题描述】:

我正在尝试寻找一种更简单的方式来读取文本文件。我以前从未用 C 编程过,所以这对我来说是全新的。我的目标是能够运行我的程序并让它自动打印到屏幕上。我下面的内容有效,但我每次都必须输入文件。任何帮助将不胜感激。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char ch, file_name[25];
    FILE *fp;

       printf("Enter name of a file you wish to see\n");
       gets(file_name);

       fp = fopen(file_name, "r"); // read mode

       if (fp == NULL)
       {
          perror("Error while opening the file.\n");
          exit(EXIT_FAILURE);
       }

       printf("The contents of %s file are:\n", file_name);

       while((ch = fgetc(fp)) != EOF)
          printf("%c", ch);

       fclose(fp);
       return 0;
}

这是输出:

Enter name of a file you wish to see
warning: this program uses gets(), which is unsafe.
Data.txt
The contents of Data.txt file are:
1
2
3
4
5
6
7
8
9
10

【问题讨论】:

  • 旁白:char ch 应该是函数fgetc() 返回的int ch
  • 如果要每次都打开同一个文件,使用char file_name[] = "Data.txt";
  • 使用gets()这句话你学到了什么?
  • ...尤其是缓冲区这么小file_name[25];
  • @JohnFore 我已经更新了您接受的答案,以确保完整性和后代。也许调查不同的选项将帮助您了解 C 允许您解决问题的多种方式。

标签: c file file-io


【解决方案1】:

您会一直阅读 Data.txt 吗?如果是这样,您可以硬编码文件名并将 gets(file_name); 替换为 char * file_name = "Data.txt" 。如果您这样做,还会删除 file_name 的当前定义以避免重新定义错误。

【讨论】:

    【解决方案2】:

    有几种方法可以在无需用户干预的情况下定义文件名。在所有情况下,删除

    printf("Enter name of a file you wish to see\n");
    gets(file_name);
    

    gets(file_name); 替换为strcpy(file_name, "Data.txt");

    您还需要#include &lt;string.h&gt;


    file_name[25] 替换为file_name[] = "Data.txt"


    char ch, file_name[25]; 替换为char ch; char *file_name = "Data.txt"; 您还可以将字符串声明为常量:const char *file_name = "Data.txt";


    gets(file_name); 替换为snprintf(file_name, (sizeof(file_name)/sizeof(file_name[0]))-1, "Data.txt");

    sizeof(file_name)/sizeof(file_name[0]) 通过将整个数组的大小除以单个元素的长度来计算数组的最大长度。我们减 1 为字符串终止字符 '\0' 保留一个元素。

    snprintf() 允许您以编程方式构建文件名。


    删除, file_name[25]

    fp = fopen(file_name, "r"); 替换为fp = fopen("Data.txt", "r");

    printf("The contents of %s file are:\n", file_name); 替换为printf("The contents of the file are:\n");

    (注意功能丢失)

    【讨论】:

    • 为什么不只是char* file_name = "Data.txt";
    • 删除 gets() 可以防止它被覆盖。为什么不const char?为什么不snprintf()?一根绳子有多长!?
    猜你喜欢
    • 2017-08-06
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2017-06-20
    • 2021-08-02
    相关资源
    最近更新 更多