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?
Two approaches leap to mind.
First, don't use
scanf
. Usefgets()
which takes a parameter to specify the buffer size, and which leaves any newline characters intact. A simple loop over the file that prints the buffer content should naturally copy the file intact.Second, use
fread()
or the common C idiom withfgetc()
. These would process the file in fixed-size chunks or a single character at a time.If you must process the file over white-space delimited strings, then use either
fgets
orfread
to read the file, and something likestrtok
to split the buffer at whitespace. Don't forget to handle the transition from one buffer to the next, since your target strings are likely to span the buffer boundary.If there is an external requirement to use
scanf
to do the reading, then limit the length of the string it might read with a precision field in the format specifier. In your case with a 999 byte buffer, then sayscanf("%998s", str);
which will write at most 998 characters to the buffer leaving room for the nul terminator. If single strings longer than your buffer are allowed, then you would have to process them in two pieces. If not, you have an opportunity to tell the user about an error politely without creating a buffer overflow security hole.Regardless, always validate the return values and think about how to handle bad, malicious, or just malformed input.
Instead just directly print the characters onto the console because the text file maybe very large and you may require a lot of memory.