I would like to copy text from text file to
How to copy text file to string in C?
FILE *file;
file = fopen ( filename, "r" );
and I assign it in variable like that
// char P[] = "Content from File";
I would like to copy text from text file to
How to copy text file to string in C?
FILE *file;
file = fopen ( filename, "r" );
and I assign it in variable like that
// char P[] = "Content from File";
There's a couple ways this can be done. My personal favourite is to use fread()
like this:
// Open the file the usual way.
File *file = fopen(filename, "r");
if(!file) exit(1); // Failed to open the file.
// Figure out the length of the file (= number of chars)
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fseek(file, 0, SEEK_SET);
// Create the char-array and read the file-content.
char *P = malloc(size * sizeof(char)) // Allocate enough space.
if(!P) exit(2); // Failed to allocate memory.
fread(P, sizeof(char), size, file); // Read the file content.
Here's an explanation as to how it works:
fseek(file, 0, SEEK_END)
Takes the file-stream file
, and sets the stream-position to the end of the file (indicated by SEEK_END
) with no offset (hence the 0
). You can read more about this std-library function here.ftell(file)
takes the file-stream file
and returns the current stream-position (which we have previously set to be the end of the file, so this will give us the length of the entire file). This value is being returned as a long int. You can read more about it here.fseek()
again, this time giving it the position-argument SEEK_SET
. This tells it to jump back to the start of the file.P
. (After a malloc, don't forget to check if you actually got a valid pointer back!)fread()
takes four arguments. The first one is the buffer to which we are going to write. This is the P
char-array in your case. The second argument, sizeof(char)
, tells fread()
what size the individual elements are going to be. In our case, we want to read characters, so we pass it the size of a character. The third argument is the length of the file, which we have previously determined. The last argument is the file-stream which should be read. If you want to read up on fread()
, you can do that here.