【问题标题】:Reading a File and storing it into an array in C读取文件并将其存储到 C 中的数组中
【发布时间】:2020-12-26 23:37:44
【问题描述】:

在通过数组从文本文件中读取第一行输入并打印它时,我需要一些帮助。 我的代码现在打印出一个巨大的数字,我不是在寻找它。

我的文本文件:

5
My first cat
csc221
My favorite

我目前的代码:

            FILE *myFile;
            char ar[1];


            myFile = fopen("‪mcPro1.txt", "r");

            fgets(ar,1,myFile);


            int x = atoi(ar);  //Convert it to a string

            printf("%d\n", ar);

            fclose(myFile);

【问题讨论】:

  • char a[1] 是单个字符。那不能保存任何有用的 C 字符串数据。
  • 在什么操作系统上? Linux(和 POSIX)有 mmap(2),对于 small 文件 - 几 GB - 可能更方便(与open(2)stat(2) 一起使用;阅读Advanced Linux Programmingsyscalls(2) 了解更多信息)
  • 否则,请阅读Modern C,然后阅读this C reference,然后阅读编译器(例如GCC...)和调试器(例如GDB...)的文档
  • 在编译器中启用所有警告和调试信息。如果您使用GCC,请使用gcc -Wall -Wextra -g。你的代码有undefined behavior 因为buffer overflow
  • 我在 Windows 上使用 Code Block atm。

标签: arrays c string file integer


【解决方案1】:

尝试使用 fscanf。下面的代码取自here,但我尝试对其进行编辑以尝试您的情况。

#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
    char ar[1];
    FILE *fptr;
    if ((fptr = fopen("mcPro1.txt", "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }

    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", ar);
    printf("Data from the file:\n%s", ar);
    fclose(fptr);

    return 0;
}

如果您希望变量 ar 的大小完全适合正在读取的字符串的大小,请尝试查找内存分配,例如 realloc()。参考this website

【讨论】:

    【解决方案2】:

    你可以使用

    c = fgetc(myfile);
    while(c != EOF)
    {
        printf("%c", c);
        c = fgetc(myfile);
    }
    

    更多信息请参考https://www.geeksforgeeks.org/c-program-print-contents-file/

    【讨论】:

      【解决方案3】:

      创建大小合适的变量以包含文件内容的步骤可能包括以下内容:

      以下是一个示例,使用 VLA 方法:(避免释放内存的需要。)

      unsigned long sizeInBytes = fsize(".\\‪mcPro1.txt")
      char ar[sizeInBytes];
      //Then fgets becomes:
      fgets(ar,sizeInBytes,myFile);
      

      fsize(".\\‪mcPro1.txt") 可以定义为:

      unsigned long fsize(char* file)
      {
          if(!file) return 0UL;
          FILE * f = fopen(file, "r");
          if(!f) return 0UL;
          if(fseek(f, 0, SEEK_END) != 0) return 0UL;
          unsigned long len = (unsigned long)ftell(f);
          fclose(f);
          return len;
      }
      

      只要文件的内容可转换为整数值,其余代码就应该可以正常工作。

      【讨论】:

        猜你喜欢
        • 2021-07-10
        • 2018-05-30
        • 2011-02-11
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 2020-02-09
        相关资源
        最近更新 更多