标准C库之文件编程

标准C库的文件编程这一块代码和Linux库的文件编程特别像,看下面几个示例就能懂了

因为是标准C库,所以头文件直接是include<stdio.h>

函数原型
fopen:FILE *fopen(const char *pathname, const char *mode);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
int fseek(FILE *stream, long offset, int whence);//

mode:
  r 以只读方式打开文件,该文件必须存在。
  r+ 以可读写方式打开文件,该文件必须存在。
  rb+ 读写打开一个二进制文件,允许读写数据,文件必须存在。
  w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
  w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
学习一般用“w+”即可

参数whence说明(来自Linux man手册):
SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file(头), the current position indicator(当前), or end-of-file(尾),respectively.

以下几个示例几乎一模一样留意返回值

#include<stdio.h>
#include<string.h>
int main()
{
    
    
        FILE *fp;
        char str[128] = {
    
    0};
        char *p = "lishun 666";


	fp = fopen("./LS","w+");
      	
    int nwrite = fwrite(p,sizeof(char)*strlen(p),1,fp);//写一次,写的大小为sizeof(char)*strlen(p)

	fseek(fp,0,SEEK_SET);

	int nread = fread(str,sizeof(char)*strlen(p),1,fp);//读一次,一次读的大小为sizeof(char)*strlen(p)

	printf("str : %s\n",str);
 	printf("nwrite = %d , nread = %d\n",nwrite,nread);  // 1 1 

	return 0;
}
#include<stdio.h>
#include<string.h>

int main()
{
    
    
        FILE *fp;
        char str[128] = {
    
    0};
        char *p = "lishun 666";


	fp = fopen("./LS","w+");
      	
    int nwrite = fwrite(p,sizeof(char),strlen(p),fp);

	fseek(fp,0,SEEK_SET);

	int nread = fread(str,sizeof(char),strlen(p),fp);

	printf("str : %s\n",str);
 	printf("nwrite = %d , nread = %d\n",nwrite,nread); // 10 10

	return 0;
}
#include<stdio.h>
#include<string.h>

int main()
{
    
    
        FILE *fp;
        char str[128] = {
    
    0};
        char *p = "lishun 666";


	fp = fopen("./LS","w+");
      	
    int nwrite = fwrite(p,sizeof(char)*strlen(p),1,fp);

	fseek(fp,0,SEEK_SET);

	int nread = fread(str,sizeof(char)*strlen(p),100,fp);//看似读100次,实际上只读了一次,因为一次刚好够了。

	printf("str : %s\n",str);
 	printf("nwrite = %d , nread = %d\n",nwrite,nread);  // 1,1

	return 0;
}

猜你喜欢

转载自blog.csdn.net/shun1296/article/details/113889127