企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 获取光标位置ftell ~~~ #include<stdio.h> long ftell(FILE * stream); 功能: 获取文件流(文件光标)的读写位置 参数: stream: 已经打开的文件指针 返回值: 成功: 当前文件流(文件光标)的读写位置 失败: -1 ~~~ # 获取文件状态stat ~~~ #include<sys/types.h> #include<sys/stat.h> int stat(const char * path, struct stat * buf); 功能: 获取文件状态信息 参数: path: 文件名 buf: 保存文件信息的结构体 返回值: 成功: 0 失败: -1 ~~~ ![](https://box.kancloud.cn/ee7c342f7402f4d5ace5d28b55b94805_1082x600.png) ~~~ #include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> int main() { struct stat s; stat("/Users/jdxia/Desktop/study/studyc++/b.txt", &s); printf("文件字节大小: %d\n", s.st_size); getchar(); return 0; } ~~~ # 删除,重命名文件 **删除文件remove** ~~~ #include<stdio.h> int remove(const char * pathname); 功能:删除文件 参数: pathname: 文件名 返回值: 成功: 0 失败: -1 ~~~ **重命名rename** ~~~ #include<stdio.h> int rename(const char * oldpath, const char * newpath); 功能: 把oldpath的文件名改为newpath 参数: oldpath: 旧文件名 newpath: 新文件名 返回值: 成功: 0 失败: -1 ~~~ # 文件缓冲区 更新缓冲区 ~~~ #include<stdio.h> int fflush(FILE *stream); 功能: 更新缓冲区,让缓冲区的数据立马写到文件中 参数: stream: 文件指针 返回值: 成功: 0 失败: -1 ~~~ # 案例 ## vi 实现 ~~~ #include <stdio.h> #include<string.h> #include<stdlib.h> int main() { //指定一个文件名 char fileName[256]; printf("请输入文件名: \n"); scanf("%s", fileName); //注意问题,用来接收换行 getchar(); //2. 打开文件 FILE *fp = fopen(fileName, "w"); //3. 判断文件的可用性 if (!fp) { return -1; } //4. 循环写入内容 char buf[1024]; while (1) { memset(buf, 0, 1024); fgets(buf, 1024, stdin); //5. 退出命令 comm=exit quit if (!strncmp("comm=exit", buf, 9)) { break; } //6.将字符串写入文件中 int i = 0; while (buf[i]) { fputc(buf[i++], fp); } //更新缓冲区 fflush(fp); } //7、关闭文件 fclose(fp); getchar(); return 0; } ~~~ ## cat实现 ~~~ #include <stdio.h> #include<string.h> #include<stdlib.h> int main() { //指定一个文件名 char fileName[256]; printf("请输入文件名: \n"); scanf("%s", fileName); //注意问题,用来接收换行 getchar(); //打开文件 FILE *fp = fopen(fileName, "r"); if (!fp) { return -1; } //文件的结束标志 EOF -1 char ch; while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); } //关闭文件 fclose(fp); getchar(); return 0; } ~~~