首页 > 代码库 > C语言读写文件

C语言读写文件

1.文件写入

追加方式:

void appendwt(){	FILE *pFile = fopen("data.txt","ab+");//使用"ab+"每次都插入到最后面,调用fseek也没用	char *str="hello,world!45%13ad2014/23/13add\n";	    fwrite(str,1,strlen(str),pFile);	    fflush(pFile);	    fclose(pFile);}

 半中间覆盖:

void randwt(){FILE *fp;        fp=fopen("overwrite.bin","rb+"); //使用rb+模式,可以往半中间插入数据,定义到任何位置        {            if(-1 == (fseek(fp,9, SEEK_SET))) /从第9字节开始abcde                    printf("seek error\n");            fwrite("abcde",1, 5, fp);
            fflush(fp);//flush来刷新流,每次读写后都希望立即看到结果,不用重新打开关闭 fclose(fp); } else { printf("fopen error"); }}

 完全覆盖:

void overwt() {	FILE *pFile = fopen("data.txt","w+");	    fwrite("hello,world!",1,strlen("hello,world!"),pFile);	    fflush(pFile);                    
            //fseek来移动文件的指针,它指向文件下一个要写入的位置 fseek(pFile,0,SEEK_SET); //文件指针设为起点,写操作覆盖原来的内容 fwrite("欢迎访问",1,strlen("欢迎访问"),pFile); fseek(pFile,0,SEEK_END); //文件指针设为终点 int len = ftell(pFile); //获取文件字节数 char* ch = (char*)malloc(sizeof(char)* (len+1)); //分配内存,多一个字节 memset(ch,0,(len+1)); //清0 // fseek(pFile,0,SEEK_SET); //文件指针指向头部 rewind(pFile); fread(ch,1,len,pFile); //读取文件 fclose(pFile); printf("%s",ch);}

 写入结构体:

typedef struct {	char c;	int h;	short n;	long m;	float f;	double d1;	char *s;	double d2;} st;
void struwt() {	FILE *fp;	st sa, sb; //定义结构体	char *str = "abcdefg"; //结构体赋值	sa.c = ‘K‘;	sa.h = -3;	sa.n = 20;	sa.m = 100000000;	sa.f = 33.32f;	sa.d1 = 78.572;	sa.d2 = 33.637;	sa.s = str;	fp = fopen("st.txt", "w+"); //打开要写的文件	if (!fp) {		printf("errror!\n");		exit(-1);	}	printf("sa:c=%c,h=%d,n=%d,m=%d,f=%f,d1=%f,s=%s,d2=%f\n", sa.c, sa.h, sa.n,			sa.m, sa.f, sa.d1, sa.s, sa.d2);	printf("sizeof(sa)=%d:&c=%x,&h=%x,&n=%x,&m=%x,&f=%x,&d1=%x,&s=%x,&d2=%x\n",			sizeof(sa), &sa.c, &sa.h, &sa.n, &sa.m, &sa.f, &sa.d1, &sa.s,			&sa.d2);	fwrite(&sa, sizeof(sa), 1, fp); //写入结构体	rewind(fp); //重新指向流	fread(&sb, sizeof(sb), 1, fp); //用sb读取	printf("sb:c=%c,h=%d,n=%d,m=%d,f=%f,d1=%f,s=%s,d2=%f\n", sb.c, sb.h, sb.n,			sb.m, sb.f, sb.d1, sb.s, sb.d2);	fclose(fp); //关闭指针}

 2.文件读取

读取结构体:

//从文件读取结构体void strurd() {	FILE *fp;	st sb;	fp = fopen("st.txt", "r"); //打开文件	if (!fp) {		printf("errror!\n");		exit(-1);	}	fread(&sb, sizeof(sb), 1, fp); //读取结构体	printf("sb:c=%c,h=%d,n=%d,m=%d,f=%f,d1=%f,s=%s,d2=%f\n", sb.c, sb.h, sb.n,			sb.m, sb.f, sb.d1, sb.s, sb.d2);	printf("sizeof(sb)=%d:&c=%x,&h=%x,&n=%x,&m=%x,&f=%x,&d1=%x,&s=%x,&d2=%x\n",			sizeof(sb), &sb.c, &sb.h, &sb.n, &sb.m, &sb.f, &sb.d1, &sb.s,			&sb.d2);	fclose(fp);}

 

scanf后加一个getchar()或者getch()来提示结束输入

继续参考:

http://blog.csdn.net/thefutureisour/article/details/8133931

http://www.cnblogs.com/songQQ/archive/2009/11/25/1610346.html

C语言读写文件