读取整个文本文件导入在C字符数组 [英] Reading the whole text file into a char array in C
问题描述
我想读一个文本文件的内容到C.换行字符数组必须保持。
我如何做到这一点?我在网上找到了一些C ++的解决方案,但没有C解决方案。
编辑:我有以下的$ C $现在C:
无效*的loadFile(字符*文件,为int *的大小)
{
FILE * FP;
长LSIZE;
字符*缓冲区; FP = FOPEN(文件,RB);
如果(FP!)PERROR(文件),出口(1); fseek的(FP,0L,SEEK_END);
LSIZE = FTELL(FP);
倒带(FP); / *的全部内容分配内存* /
缓冲液=释放calloc(1,LSIZE + 1);
如果FCLOSE(FP)的fputs(记忆ALLOC失败,标准错误),出口(1)(缓冲!); / *将文件复制到缓冲器* /
如果(1!=的fread(缓冲液,LSIZE,1,FP))
FCLOSE(FP),自由(缓冲区)的fputs(整个读取失败,标准错误),出口(1); / *做你的工作在这里,缓冲区是一个字符串包含整个文本* /
大小=(INT *)LSIZE;
FCLOSE(FP);
返回缓冲区;
}
我得到一个警告:警告:赋值时将整数指针,未作演员。这是上线尺寸=(INT)LSIZE;
。如果我运行应用程序,它出现segfaults。
的更新:的上述code现在的作品。我所在的段错误,而我张贴另一个问题。感谢您的帮助。
FILE * FP;
长LSIZE;
字符*缓冲区;FP = FOPEN(blah.txt,RB);
如果PERROR(blah.txt),退出(1)(FP!);fseek的(FP,0L,SEEK_END);
LSIZE = FTELL(FP);
倒带(FP);/ *的全部内容分配内存* /
缓冲液=释放calloc(1,LSIZE + 1);
如果FCLOSE(FP)的fputs(记忆ALLOC失败,标准错误),出口(1)(缓冲!);/ *将文件复制到缓冲器* /
如果(1!=的fread(缓冲液,LSIZE,1,FP))
FCLOSE(FP),自由(缓冲区)的fputs(整个读取失败,标准错误),出口(1);/ *做你的工作在这里,缓冲区是一个字符串包含整个文本* /FCLOSE(FP);
免费(缓冲);
I want to read the contents of a text file into a char array in C. Newlines must be kept.
How do I accomplish this? I've found some C++ solutions on the web, but no C only solution.
Edit: I have the following code now:
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;
}
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屋!