File read and write functions

Reference in this blog two pairs of file read and write functions for simple finishing.
1.fscanf (), fprintf () to read and write files for formatting
function prototypes

int fscanf ( FILE *fp, char * format, ... );
int fprintf ( FILE *fp, char * format, ... );

That is, in the original scanf () and printf () function more parameters based on the FILE *fp(file handle).
When the first parameter to stdin, consistent with the fscanf () and scanf () action.
Format control character string to be noted that the data to be inputted type parameters consistent output!

int main()
{
   FILE * fp;
   char c[]="Hello world!";
   char buffer[20];

   fp = fopen ("file.txt", "w+");
   fprintf(fp,"%s",c);
  
   rewind(fp);	//定位到文件的开头。
   while(!feof(fp))
   {
   fscanf(fp, "%s", buffer); 
   printf("%s ", buffer);
   } 
   printf("%s\n", buffer);
   fclose(fp);
   
   return(0);
}

2. The data block read and write file functions: fread (), fwrite () Function
Function Prototype

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
size_t fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)

I.e. nmemb read element of size from a given size of the array to the data stream stream pointed to by ptr.

int main()
{
   FILE *fp;
   char c[] = "hello world!";
   char buffer[20];
 
   /* 打开文件用于读写 */
   fp = fopen("file.txt", "w+");
 
   /* 写入数据到文件 */
   fwrite(c, strlen(c) + 1, 1, fp);
 
   /* 查找文件的开头 */
   fseek(fp, 0, SEEK_SET);
 
   /* 读取并显示数据 */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp); 
   return(0);
}

Compared with fscanf and fprintf, fread and fwrite block of data read, read faster. But they are defective, that is, when read while (! Feof (fp)) inaccurate, often find it more than once cycle. Since feof () is to determine whether the end of the file according to the remaining characters, the end of the file identifier is '/ 0' is two bytes, read '/' when feof () is false, or only Read End '/ 0' when feof () == true. Resulting in generating extra cycle. However, because of the format of the data gave an accurate provisions, this problem does not occur in the fscanf and fprintf in!

Released two original articles · won praise 0 · Views 48

Guess you like

Origin blog.csdn.net/weixin_44091012/article/details/104612506