C语言 将整个文本文件读入 C 中的字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3747086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading the whole text file into a char array in C
提问by friedkiwi
I want to read the contents of a text file into a char array in C. Newlines must be kept.
我想将文本文件的内容读入 C 中的字符数组。必须保留换行符。
How do I accomplish this? I've found some C++ solutions on the web, but no C only solution.
我该如何实现?我在网上找到了一些 C++ 解决方案,但没有只有 C 的解决方案。
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.
我收到一个警告:警告:赋值使指针从整数而不进行强制转换。这个就行了size = (int)lSize;。如果我运行该应用程序,它会出现段错误。
Update:The above code works now. I located the segfault, and I posted another question. Thanks for the help.
更新:上面的代码现在可以工作了。我找到了段错误,并发布了另一个问题。谢谢您的帮助。
回答by user411313
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);
回答by Emmet
A solution in the form of a complete program that answers the question and demonstrates it. It is a bit more explicit than other answers and, therefore, easier to understand for those less experienced in C(IMHO).
一个完整程序形式的解决方案,可以回答问题并演示它。它比其他答案更明确,因此对于那些在C方面经验不足的人来说更容易理解(恕我直言)。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*
* 'slurp' reads the file identified by 'path' into a character buffer
* pointed at by 'buf', optionally adding a terminating NUL if
* 'add_nul' is true. On success, the size of the file is returned; on
* failure, -1 is returned and ERRNO is set by the underlying system
* or library call that failed.
*
* WARNING: 'slurp' malloc()s memory to '*buf' which must be freed by
* the caller.
*/
long slurp(char const* path, char **buf, bool add_nul)
{
FILE *fp;
size_t fsz;
long off_end;
int rc;
/* Open the file */
fp = fopen(path, "rb");
if( NULL == fp ) {
return -1L;
}
/* Seek to the end of the file */
rc = fseek(fp, 0L, SEEK_END);
if( 0 != rc ) {
return -1L;
}
/* Byte offset to the end of the file (size) */
if( 0 > (off_end = ftell(fp)) ) {
return -1L;
}
fsz = (size_t)off_end;
/* Allocate a buffer to hold the whole file */
*buf = malloc( fsz+(int)add_nul );
if( NULL == *buf ) {
return -1L;
}
/* Rewind file pointer to start of file */
rewind(fp);
/* Slurp file into buffer */
if( fsz != fread(*buf, 1, fsz, fp) ) {
free(*buf);
return -1L;
}
/* Close the file */
if( EOF == fclose(fp) ) {
free(*buf);
return -1L;
}
if( add_nul ) {
/* Make sure the buffer is NUL-terminated, just in case */
buf[fsz] = 'char* load_file(char const* path)
{
char* buffer = 0;
long length;
FILE * f = fopen (path, "rb"); //was "rb"
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = (char*)malloc ((length+1)*sizeof(char));
if (buffer)
{
fread (buffer, sizeof(char), length, f);
}
fclose (f);
}
buffer[length] = 'FILE *fptr;
char *msg;
long length;
size_t read_s = 0;
fptr = fopen("example_test.xml", "rb");
fseek(fptr, 0L, SEEK_END);
length = ftell(fptr);
rewind(fptr);
msg = (char*)malloc((length+1));
read_s = fread(msg, 1, length, fptr);
*(mip_msg+ read_s) = 0;
if (fptr) fclose(fptr);
';
// for (int i = 0; i < length; i++) {
// printf("buffer[%d] == %c\n", i, buffer[i]);
// }
//printf("buffer = %s\n", buffer);
return buffer;
}
';
}
/* Return the file size */
return (long)fsz;
}
/*
* Usage message for demo (in main(), below)
*/
void usage(void) {
fputs("USAGE: ./slurp <filename>\n", stderr);
exit(1);
}
/*
* Demonstrates a call to 'slurp'.
*/
int main(int argc, char *argv[]) {
long file_size;
char *buf;
/* Make sure there is at least one command-line argument */
if( argc < 2 ) {
usage();
}
/* Try the first command-line argument as a file name */
file_size = slurp(argv[1], &buf, false);
/* Bail if we get a negative file size back from slurp() */
if( file_size < 0L ) {
perror("File read failed");
usage();
}
/* Write to stdout whatever slurp() read in */
(void)fwrite(buf, 1, file_size, stdout);
/* Remember to free() memory allocated by slurp() */
free( buf );
return 0;
}
回答by Shark
Since I used slurp()expecting it to work, a few days later I found out that.... it doesn't.
因为我曾经slurp()期望它可以工作,几天后我发现......它没有。
So for people that are eager to copy/paste a solution to "getting the contents of a FILE into a char*", here's something you can use.
因此,对于渴望复制/粘贴“将 FILE 的内容转换为 char*”的解决方案的人来说,您可以使用以下方法。
##代码##回答by Shamim Hafiz
fgets() is a C function that can be used to accomplish this.
fgets() 是可用于完成此操作的 C 函数。
Edit:You can also consider using fread().
编辑:您也可以考虑使用 fread()。
回答by sreaga
I have used following code to read xml file in to a char buffer and I had to add \0 at the end of file
我使用以下代码将 xml 文件读入字符缓冲区,并且必须在文件末尾添加 \0
##代码##
