c - 读取文件到字符串

标签 c string file fgetc

我想将文件读取为字符串。

我有以下代码,可以编译但无法运行。

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

char string[50000];    

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

char buffer;


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

最佳答案

首先尝试将 string[0] 设置为 \0。另外,buffer 应该是 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.

关于c - 读取文件到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313718/

相关文章:

c - 无法在C程序中的for循环外使用变量值

Python:用列表中的第 i 个元素替换第 n 次出现的 x

string - 在matlab中用运算符和宏替换字符串

file - 文件格式存储的最佳实践 (Hadoop)

java - 包 View 中的 IntelliJ : Display . java 扩展

native 可执行文件的 Android NDK 分析器不生成任何数据

c - 在生成过程中获取值

java - 在 Java 中对齐文本

java - 将文本行添加到文本文件的最佳策略

c - C 中的函数语法