c - C语言读取一个TXT文件中的所有字符

标签 c arrays file file-io

<分区>

我正在尝试编写一个程序来读取所有 TXT 文件并将其复制到一个特定的数组中。但是,问题是空白字符。如果我使用 fscanf,我无法将所有 TXT 文件放入一个数组中。如何将 TXT 文件复制到字符数组中?

最佳答案

标准库提供了能够在一次函数调用中读取文件的全部内容所需的所有函数。您必须先计算出文件的大小,确保分配足够的内存来保存文件的内容,然后在一个函数调用中读取所有内容。

#include <stdio.h>
#include <stdlib.h>

long getFileSize(FILE* fp)
{
   long size = 0;
   fpos_t pos;
   fseek(fp, 0, SEEK_END);
   size = ftell(fp);
   fseek(fp, 0, SEEK_SET);
   return size;
}

int main(int argc, char** argv)
{
   long fileSize;
   char* fileContents;

   if ( argc > 1 )
   {
      char* file = argv[1];
      FILE* fp = fopen(file, "r");
      if ( fp != NULL )
      {
         /* Determine the size of the file */
         fileSize = getFileSize(fp);

         /* Allocate memory for the contents */
         fileContents = malloc(fileSize+1);

         /* Read the contents */
         fread(fileContents, 1, fileSize, fp);

         /* fread does not automatically add a terminating NULL character.
            You must add it yourself. */
         fileContents[fileSize] = '\0';

         /* Do something useful with the contents of the file */
         printf("The contents of the file...\n%s", fileContents);

         /* Release allocated memory */
         free(fileContents);

         fclose(fp);
      }
   }
}

关于c - C语言读取一个TXT文件中的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514171/

相关文章:

c - C中的空指针

java - 显示来自java中另一个方法的数组

c++ - glGetTexImage 读取过多纹理格式为 GL_ALPHA 的数据

linux - 平面文件数据分析

c - fwrite 不写入整个缓冲区

C float 0x1.fp3

我可以在Linux中从C代码获取SSID和MAC地址吗?

c - 未命名的 unix 域套接字地址长度错误

c - 如何在 C 中实现具有已知数字列的动态二维数组

Android 10 (api-29) 文件写入