I have a text file named test.txt
I want to write a C program that can read this file and print the content to the console (assume the file contains only ASCII text).
I don't know how to get the size of my string variable. Like this:
char str[999];
FILE * file;
file = fopen( "test.txt" , "r");
if (file) {
while (fscanf(file, "%s", str)!=EOF)
printf("%s",str);
fclose(file);
}
The size 999
doesn't work because the string returned by fscanf
can be larger than that. How can I solve this?
You could read the entire file with dynamic memory allocation, but isn't a good idea because if the file is too big, you could have memory problems.
So is better read short parts of the file and print it.
There are plenty of good answers here about reading it in chunks, I'm just gonna show you a little trick that reads all the content at once to a buffer and prints it.
I'm not saying it's better. It's not, and as Ricardo sometimes it can be bad, but I find it's a nice solution for the simple cases.
I sprinkled it with comments because there's a lot going on.
Let me know if it's useful or you could learn something from it :)
You can use
fgets
and limit the size of the read string.You can change the
while
in your code to:Use "read()" instead o fscanf:
Here is an example:
http://cmagical.blogspot.com/2010/01/c-programming-on-unix-implementing-cat.html
Working part from that example:
An alternate approach is to use
getc
/putc
to read/write 1 char at a time. A lot less efficient. A good example: http://www.eskimo.com/~scs/cclass/notes/sx13.htmlThe simplest way is to read a character, and print it right after reading:
c
isint
above, sinceEOF
is a negative number, and a plainchar
may beunsigned
.If you want to read the file in chunks, but without dynamic memory allocation, you can do:
The second method above is essentially how you will read a file with a dynamically allocated array:
Your method of
fscanf()
with%s
as format loses information about whitespace in the file, so it is not exactly copying a file tostdout
.