(资料图片)
2023/6/20 IO操作太多太杂,还有很多要注意点,不用又经常忘记,就总结一下,希望能快速回顾和查询,后续有需要在慢慢补充
一、标准IO
注意点:
- 只能操作普通文件
- C库中定义的输入输出的函数
- 有缓冲机制,减少系统调用
- 围绕流进行操作,
FILE*
描述 - 默认打开三个流
stdin
stdout
stderr
二、函数接口
1、FILE *fopen(const char *path, const char *mode); //打开文件//path格式 "./a.c" mode权限 "w"2、int fgetc(FILE *stream);//读取一个字符//从文件读一个字符,返回值是读到的ASCII3、int fputc(int c,FILE *stream);//向文件中写一个字符//返回值:成功为写的字符ASICI ,失败返回EOF4、int feof(FILE * stream);//判断文件有没有结尾5、int ferror(FILE * stream);//检查文件有么有出错6、void perror(FILE * stream);//根据errno打印错误信息7、char *fgets(char *s, int size, FILE *stream);//从文件中读取一串字符8、int fputs(const char *s, FILE *stream);//向文件中写字符串9、int fclose(FILE * stream);//关闭文件10、int fprintf(FILE *stream, const char *format, ...)11、size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);//从文件流读取多个元素12、size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);13、 void rewind(FILE * stream);//将文件位置指针定位到起始的位置14、int fseek(FILE *stream,long offset,int whence);//文件的定位操作 //whence 相对位置 offset偏移量 SEEK_SET相对于开头 SEEK_CUR 当前位置 SEEK_END
三、功能代码
打开文件
#includeint main(){ FILE* fp=fopen("./a.c","a+"); if(fp==NULL){perror("open");return -1;} fclose(fp);}
读写文件(单个字符)
int main(int argc,char const *argv[]){ FILE *fp=fopen(argv[1],"r+"); int ch=0; while( (ch=fgetc(fp))!=EOF ) printf("%c",ch); fputc("!",fp);//写一个字符 fputc("&",stdout);//向终端(标准输出)写一个字符 fclose(fp);}
读写文件(多个字符)
#include#includeint main(int argc,char const *argv[]){ FILE *fp=fopen(argv[1],"r+"); char buf[32]=""; while( fgets(buf,32,fp)!=NULL ) { if( buf[strlen(buf)-1]=="\n" ) //判断\0前面一个字符是不是\n buf[strlen(buf)-1]="\0" printf("%s\n",buf); } fclose(fp);}
实现head -n文件名功能
#include#includeint main(int argc ,char const *argv[]){ FILE* fp=fopen(argv[2],"r"); char buf[32]=""; int num=atoi(argv[1]+1); while( fgets(buf,32,fp)!=NULL ) { if(buf[strlen(buf)-1]=="\n") buf[strlen(buf)-1]="\0"; int n=0;n++; printf("%s", buf); if(n==num)break; } return 0;}
二进制读写
#include int main(int argc, char const *argv[]){ FILE *fp; int arr[3] = {10, 20, 30}, num[3] = {0}; fp = fopen("a.c", "w+"); if(fp == NULL) { perror("fopen err"); return -1; } fwrite(arr, sizeof(int), 3, fp); //将文件位置移动到文件开头 rewind(fp); fread(num, sizeof(int), 3, fp); for(int i = 0; i < 3; i++) printf("%d\n", num[i]); return 0;}
额外功能补充
计时器问题。
#include #include #include #include #include //功能需求:每隔了一秒,向文件写入一段时间int main(){ FILE* fp=fopen("time.txt","w+"); char ch[200]; time_t rawtime; struct tm *info; while(1) { time(&rawtime); info = localtime(&rawtime); fprintf(fp, "%d %d-%d-%d%d:%d:%d\n", ++count, info->tm_year + 1900, info->tm_mon + 1, info->tm_mday, info->tm_hour, info->tm_min, info->tm_sec); printf("%d %d-%d-%d%d:%d:%d\n", count, info->tm_year + 1900, info->tm_mon + 1, info->tm_mday, info->tm_hour, info->tm_min, info->tm_sec); fflush(fp);//刷新一下缓存区 sleep(1); } fclose(fp); return 0; }
标签: