A. standard file programming library functions for file state:
#include <stdio.h>
1.int ferror (file* stream);//is only used to determine whether the error occurred, not clear the wrong content
When the file IO error occurs, FERROR returns non 0, successfully returning 0
2.int feof (file* stream);//is only used to determine whether the error occurred, not clear the wrong content
When the file ends, Feof returns non 0, otherwise returns 0
Use the above two functions:
Read the file and exit automatically when the file ends
int main ()
{
file* FP;
Char buf[1024];
1. Commonly used methods of judging errors
if (fp = fopen ("/etc/passwd", "r") = = = NULL)
{
fprintf (stderr, "Error:%s", "Open file passwd failed");
Perror ("/etc/passwd");
Exit (1);
}
2. Use Ferror to determine if a file has errors
fp = fopen ("/etc/passwd", "R");
if (ferror (FP))
{
fprintf (stderr, "Error:%s", "Open file passwd failed");
Perror ("/etc/passwd");
Exit (1);
}
1. General method of determining the end of a document
while (Fgets (buf,sizeof (BUF), fp)! = NULL)
{
if (fputs (buf,stdout) = = EOF)
{
fprintf (stderr, "error:%s", "Fput filed");
Break
}
}
2. Use feof to determine the end of the file
while (!feof (FP))//Do not exit the loop without ending
{
Fgets (Buf,sizeof (BUF), FP);
if (feof (FP))
Break
Fputs (buf,stdout);
}
Fclose (FP);
}
3.void Clearerr (file* stream);
Clearerr clears the file stream error flag and the EOF flag.
Two. Functions used in the standard file programming library to determine the explicit error information of a file
When a Unix function goes wrong, it often returns a negative value or null, and the integer variable errno is usually set to one that contains additional information.
#include <string.h>
1.char* strerror (int errnum);
This function maps Errnum (usually the value of errno) to an error message string and returns a pointer to this string.
When an error occurs, call Strerror (errno) immediately to get the current error message and then print it to the standard error output stream via fprintf
Usage:
if (FD = open ("/etc/passwd", "r")) = = =-1)
{
fprintf (stderr, "error:%s", Strerror (errno));
}
#include <stdio.h>
2.void perror (const char* msg);
Determine the error and end status of a file