我想在C语言中将文本文件的内容读入char数组中,需要保留换行符。
如何实现?我在网上找到了一些C++的解决方案,但没有纯C的解决方案。
编辑:我现在有以下代码:
void *loadfile(char *file, int *size)
{
FILE *fp;
long lSize;
char *buffer;
fp = fopen ( file , "rb" );
if( !fp ) perror(file),exit(1);
fseek( fp , 0L , SEEK_END);
lSize = ftell( fp );
rewind( fp );
/* allocate memory for entire content */
buffer = calloc( 1, lSize+1 );
if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);
/* copy the file into the buffer */
if( 1!=fread( buffer , lSize, 1 , fp) )
fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);
/* do your work here, buffer is a string contains the whole text */
size = (int *)lSize;
fclose(fp);
return buffer;
}
我收到了一个警告:warning: assignment makes pointer from integer without a cast。这是在size = (int)lSize;
这一行。如果我运行应用程序,它将导致段错误。
更新:上面的代码现在可以正常工作了。我找到了段错误,并发布了另一个问题。感谢您的帮助。
size = (int *)lSize;
将本地变量指针size
设置为转换为指针的整数,但不会更新调用者传递指针的整数。(可能是你想写成*size = lSize
)。因此,这个有缺陷的答案应该被投票降低分数,但这是一个合理的问题。此外,你提到你发现(并修复)了一个段错误,但这是旧的代码还是修复后的代码?无论如何,即使它可以复制/粘贴,也不应该在问题中。 - Peter Cordes