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?
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... }
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.
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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With