赞
踩
fopen fgetc fputc fwrite fread fgets fputs
//main.c #include <stdio.h> #include <string.h> int main() { FILE *fp; int ret; //打开/创建文件 fp = fopen("test.txt", "wb+"); if (NULL == fp) { perror("fopen fail");//perror aim to find reason of error return -1; //程序退出码为-1,说r退出异常 } /* * putc写操作 */ int i=fputc('a',fp); //写入成功返回写入字符,否则 EOF if(EOF == i){ //如果提示 fputc error: Bad file descriptor,看是否读写权限有误 perror("fputc error"); } printf("putc = %c\n",i); //一般i=1 /* * getc读操作 */ char c; long long pos; fseek(fp,-1,SEEK_CUR); pos= ftell(fp); //获取位置指针距离文件开头的位置 printf("after fseek pos=%ld\n",pos); while ( (c=fgetc(fp) ) != EOF){ printf("%c",c); } printf("\nend of file\n"); pos= ftell(fp); printf("after fgetc pos=%ld\n",pos); /* * fwrite fread 读写操作-字符串 */ char buf[20]="hello\nworld"; ret = fwrite(buf,sizeof (char), strlen(buf),fp); printf("fwrite ret = %d\n",ret); fseek(fp,-strlen(buf),SEEK_CUR); memset(buf,0,sizeof (buf)); printf("%buff= %s\n",buf); ret= fread(buf,sizeof (char),sizeof (buf),fp); printf("fread ret = %d\n",ret); pos= ftell(fp); printf("after fwrite pos=%ld\n",pos); //21 /* * fwrite fread 读写操作-二进制数据-整数 */ // int num = 123456; // ret=fwrite(&num, sizeof(int), 1, fp); // printf("fwrite num ret = %d\n",ret); //1 // fseek(fp,-sizeof(int),SEEK_CUR); // num=0; // ret = fread(&num, sizeof (int), 1, fp); // printf("fread num ret = %d\n",ret); //1 // printf("num = %d\n",num); //123456 // long long pos= ftell(fp); // printf("after fwrite pos=%ld\n",pos); //16 // // /* // * fgets puts 读写操作 // * fgets替换scanf: buf是字符串数组,fgets(buf,sizeof(buf),stdin); // * 读取文件时,将stdin换为 fp,即标准输入缓冲区->文件指针 // * fputs(buf,fp) fputs(buf,stdout) // */ // char str[10]={0}; // fseek(fp,-sizeof(int),SEEK_CUR); // while (fgets(str,sizeof (str),fp) != NULL) { printf("str = |%s\n",str); // fputs(str,stdout); // } // printf("\n%d\n", strlen(str)); fclose(fp); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。