#include <stdio.h> #include <stdlib.h> #include <string.h> int test_fgets (const char* filePath) {
file* Fp=fopen (FilePath, "R");
if (fp==null) {printf ("Open error!%s", strerror (errno));
return-1;
} Char buffer[2048]={0};
while (Fgets (buffer,sizeof (buffer), FP)) {printf ("%s", buffer);
Fclose (FP);
return 0;
} char* getAllFileData2 (char *filepath) {FILE *fp;
Char *str;
Char buffer[4096];
int filesize;
if ((Fp=fopen (FilePath, "R")) ==null) {printf ("Open file%s error error=%s \ n", Filepath,strerror (errno));
return NULL;
} fseek (Fp,0,seek_end);
FileSize = Ftell (FP);
Str= (char *) malloc (filesize+1);
memset (str,0,filesize+1);
Rewind (FP);
int bufsize=sizeof (buffer); Fgets cache size can only be bufsize?
What if a row of data is very long.
while ((Fgets (BUFFER,BUFSIZE,FP))!=null) {//each time read up bufsize-1 characters strcat (str,buffer);
Fclose (FP);
return str; } char* Getallfiledata(Char *filepath)
{FILE *FP;
Char *str;
Char buffer[4096];
int filesize;
if ((Fp=fopen (FilePath, "R")) ==null) {printf ("Open file%s error error=%s \ n", Filepath,strerror (errno));
return NULL;
} fseek (Fp,0,seek_end);
FileSize = Ftell (FP);
Str= (char *) malloc (filesize+1);
memset (str,0,filesize+1);
Rewind (FP);
int bufsize=sizeof (buffer); The Fgets function succeeds in returning the BUF, failing or reading to the end of the file to return null.
Therefore, we cannot directly judge whether a function is an error by means of the return value of the fgets, and it should be judged by the feof function or the ferror function.
while (!feof (FP)) {fgets (BUFFER,BUFSIZE,FP);
strcat (Str,buffer);
Fclose (FP);
return str;
int main (void) {test_fgets ("d:/test.txt");
printf ("=====================================\n");
Char *p;
P=getallfiledata ("D:/test.txt");
if (p!=null) {puts (p);
Free (p);
return 0;
}