【问题标题】:Read file to string读取文件到字符串
【发布时间】:2013-12-01 15:21:48
【问题描述】:

我想读取一个文件到一个字符串。

我有以下代码,可以编译但不能运行。

我的想法是使用 while 循环将文件中的每个字符附加到字符串的末尾,直到 EOF。

char string[50000];    

FILE *file;
file = fopen("filename.txt", "r");

char buffer;


while((buffer=fgetc(file)) != EOF)
{
    strcat(string, buffer);
}

【问题讨论】:

  • @SharonJDDorot 我想更改第一行并将其重写到文件中。
  • 所以改为以 a+ 或 r+ 的形式打开文件(其中一个返回指向文件开头的指针并允许覆盖文本,不确定是哪个),将第一行读入 char 数组,返回指向文件开头的指针并简单地覆盖现有文本。更轻松、更高效。

标签: c string file fgetc


【解决方案1】:

先尝试将string[0] 设置为\0buffer 也应该是 char * 并且也应该以 null 结尾。

来自man 页面:

 NAME
 strcat, strncat -- concatenate strings

 LIBRARY
 Standard C Library (libc, -lc)

 SYNOPSIS
 #include <string.h>

 char *
 strcat(char *restrict s1, const char *restrict s2);

 char *
 strncat(char *restrict s1, const char *restrict s2, size_t n);

 DESCRIPTION
 The strcat() and strncat() functions append a copy of the null-terminated
 string s2 to the end of the null-terminated string s1, then add a termi-
 nating `\0'.  The string s1 must have sufficient space to hold the
 result.

【讨论】:

    【解决方案2】:

    您正在读取的缓冲区必须是一个数组。

    char buffer[50000];
    

    【讨论】:

      【解决方案3】:
        int buffer, i;
        char string[50000];
      
        FILE *file;
        file = fopen("file.txt", "r");
      
        i = 0;
      
        while ( ( buffer = fgetc( file ) ) != EOF ) {
          string[i++] = buffer;
        }
      
        printf("%s\n", string );
      

      【讨论】:

      • @Johnson:在 C 中,字符串是由特殊空字符值“\0”终止的 char 值数组。所以,如果你的意思是一个字符串,它永远不会是 1 个字符长度,而是至少 2 个或更多。
      猜你喜欢
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多