Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load a whole file into a string in C [duplicate]

Tags:

c

string

file

Possible Duplicate:
Easiest way to get file's contents in C

My program reads files that span over many lines. I would like to hold the content of a file in a single string.

I don't know the number of lines of my file before execution, however I have fixed a line size to MAX_LINE_LEN.

How can you do that?

like image 468
rahmu Avatar asked Oct 22 '11 01:10

rahmu


People also ask

How do you store the contents of a file into a string in C?

char * buffer = 0; long length; FILE * f = fopen (filename, "rb"); if (f) { fseek (f, 0, SEEK_END); length = ftell (f); fseek (f, 0, SEEK_SET); buffer = malloc (length); if (buffer) { fread (buffer, 1, length, f); } fclose (f); } if (buffer) { // start to process your data / extract strings here... }

How do I read an entire text file in C++?

Read whole ASCII file into C++ std::string txt using file object f of ifstream type to perform read operation. Declare a variable str of string type. If(f) Declare another variable ss of ostringstream type. Call rdbuf() fuction to read data of file object.

How do you print a string in C?

using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);


1 Answers

The function fread() doesn't care about line breaks. The following code reads the contents of input_file_name and saves them to the array file_contents:

char *file_contents;
long input_file_size;
FILE *input_file = fopen(input_file_name, "rb");
fseek(input_file, 0, SEEK_END);
input_file_size = ftell(input_file);
rewind(input_file);
file_contents = malloc(input_file_size * (sizeof(char)));
fread(file_contents, sizeof(char), input_file_size, input_file);
fclose(input_file);

You can only make a string of this array if input_file_name contains the \0 character. If it does not, change the last three lines to:

file_contents = malloc((input_file_size + 1) * (sizeof(char)));
fread(file_contents, sizeof(char), input_file_size, input_file);
fclose(input_file);
file_contents[input_file_size] = 0;
like image 114
Dennis Avatar answered Oct 11 '22 20:10

Dennis