将整个文本文件读入 C 中的字符数组 [英] Reading the whole text file into a char array in C

查看:22
本文介绍了将整个文本文件读入 C 中的字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文本文件的内容读入 C 中的字符数组中.必须保留换行符.

I want to read the contents of a text file into a char array in C. Newlines must be kept.

我如何做到这一点?我在网上找到了一些 C++ 解决方案,但没有仅使用 C 的解决方案.

How do I accomplish this? I've found some C++ solutions on the web, but no C only solution.

我现在有以下代码:

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;
}

我收到一个警告:警告:赋值使指针来自整数而不进行强制转换.这是 size = (int)lSize; 行.如果我运行该应用程序,它会出现段错误.

I get one warning: warning: assignment makes pointer from integer without a cast. This is on the line size = (int)lSize;. If I run the app, it segfaults.

更新: 上面的代码现在可以工作了.我找到了段错误,并发布了另一个问题.感谢您的帮助.

Update: The above code works now. I located the segfault, and I posted another question. Thanks for the help.

推荐答案

FILE *fp;
long lSize;
char *buffer;

fp = fopen ( "blah.txt" , "rb" );
if( !fp ) perror("blah.txt"),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 */

fclose(fp);
free(buffer);

这篇关于将整个文本文件读入 C 中的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆