Problem reading the contents of the text file and displaying it as a string
I have a text file named MySQL.txt having the following contents :
MySQL_IP:172.19.1.173
MySQL_USER:kok
MySQL_PASS:kok
MySQL_DATABASE:kok
I am trying to read the contents of the file using the following code
#include<stdio.h>
main()
{
FILE *fp;
char str[50000];
fp = fopen("MySQL.txt","r");
fgets(str,sizeof(str),fp);
printf("%s\n",str);
}
No matter how much i increase the size of the string buffer,i am provided with teh output which is :
MySQL开发者_开发百科_IP:172.19.1.173
which is just the first line...I fail to fathom the reason !!!
There is documentation that you can use and look up easily on your favorite search engine which will tell you the answer. For example, as described on this page for fgets()
:
The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.
If you need to read in the entire file at once, use fread()
instead of fgets()
. Unlike fgets()
, fread()
will not stop reading on occurrence of a newline.
If you want to process the file line-by-line, then call fgets()
repeatedly until feof()
returns a non-zero value (indicating EOF) or ferror()
returns a non-zero value (indicating an error condition).
fgets
reads a line, i.e.: until the next \n
(newline) in the text or end of file.
To read the whole file, you need to repeat the sequence until feof
returns true.
fgets documention says :
syntex :
char * fgets ( char * str, int num, FILE * stream );
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string.
so here fgets only read upto 1st line so i suggest u to use fread()
精彩评论