相关疑难解决方法(0)

将整个文本文件读入C中的char数组

我想将文本文件的内容读入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); …
Run Code Online (Sandbox Code Playgroud)

c file-io text

30
推荐指数
3
解决办法
8万
查看次数

标签 统计

c ×1

file-io ×1

text ×1