【问题标题】:Reading the contents from a file从文件中读取内容
【发布时间】:2013-12-24 19:32:26
【问题描述】:

我想将 .txt 文件的内容保存到数组中。这里的事情是我首先使用该位置到另一个数组中,并且我想使用该数组保存我的位置来将文件的内容存储到一个数组中。 该代码似乎不起作用。帮助表示赞赏。

#include <stdio.h>
#include <string.h>
int main()
{
   char location[50],input[1000]={0};
   int i=0; 
   printf("Enter your file location:\n");
   scanf("%999[^\n]",location);

   FILE *ptr;
   ptr = fopen("location", "r");

   while(!EOF)
   {
     char c;
     c = (char) fgetc(ptr);
     input[i] = c;
     printf("%c", input[i]);
     i++;
   }
   input[i] = NULL;
   printf("%s",input);
   getch();
   return 0;
}

【问题讨论】:

  • fopen("location","r"); - 确定要"location" 而不是location

标签: c arrays string file


【解决方案1】:

EOF is something different(它是一个宏,因此!EOF 始终是一个常量值,实际上并不检查任何内容)。也许您打算使用feof()。或者,更确切地说:

int c;
while ((c = fgetc(ptr)) != EOF)
{
    ...

【讨论】:

    【解决方案2】:

    多个问题

    1. scanf() 中的缓冲区大小错误,应测试结果。

      char location[50];
      // scanf("%999[^\n]",location);
      if (1 != scanf("%49[^\n]",location)) HandleError();
      
    2. fopen() (@Mat) 的参数错误。添加测试

      // ptr = fopen("location", "r");
      ptr = fopen(location, "r");
      if (ptr == NULL) HandleOpenError();
      
    3. 错误使用 EOF 和 c 类型 (@Cornstalks)

      // while(!EOF) {
      //  char c;
      // c = (char) fgetc(ptr);
      int c;
      while ((c = fgetc(ptr)) != EOF) {
      
    4. 错误的终止。

      // input[i] = NULL;
      input[i] = '\0';
      
    5. 如果文件长度 >= 1000 则为 UB;
      检查@Fiddling Bits 为整个文件分配缓冲区的答案。
      建议使用size_t fileLength 而不是long int fileLength
      添加free(pFileContents);

    6. 没有fclose()

       fclose(ptr);
       return 0;
      
    7. 次要:如果文本文件异常且嵌入了\0printf("%s",input); 将不会打印出整个文件。

    【讨论】:

      【解决方案3】:

      首先,你必须确定文件的长度:

      fseek(ptr, 0, SEEK_END);
      long int fileLength = ftell(ptr);
      

      然后,创建一个足够大的缓冲区来保存文件的全部内容:

      char *pFileContents = malloc(fileLength);
      if(!pFileContents)
          return -1; // Error
      

      最后,将文件内容复制到新创建的缓冲区中:

      rewind(ptr);
      if(fread(pFileContents, 1, fileLength, ptr) != fileLength)
          return -1; // Error
      fclose(ptr);
      

      【讨论】:

        猜你喜欢
        • 2017-04-19
        • 2017-08-13
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-18
        相关资源
        最近更新 更多