C文件操作
打开文件
FILE *fopen(const char * filename, const char * mode);
常见的mode有:
‘a’:打开已有或创建文件,在原有内容上追加内容。
mode | Description |
---|---|
r | 打开已有文本允许读取文件 |
w | 打开已有或创建文件,允许写入,如果是已有文件要删掉内容重新写入 |
a | 打开已有或创建文件,在原有内容上追加内容 |
r+ | 打开文本文件,允许读写 |
w+ | 打开文本文件,允许读写,如果是已有文件要删掉内容重新写入 |
a+ | 打开文本文件,允许读写,在原有内容上追加内容 |
关闭文件
清空缓冲区数据并关闭文件
int fclose(FILE *fp);
写入文件
可以使用fprintf() 函数将一个字符串写入到文件中;
int fprintf(FILE *fp, const char *format, ...)
示例:
#include <stdio.h>
int main() {
FILE *fp = NULL;
fp = fopen("test.txt", "w+");
fprintf(fp, "This is testing programme.\n");
fclose(fp);
return 0;
}
读取文件
- 函数fgetc() 从 fp 所指向的输入文件中读取一个字符。返回值是读取的字符,如果发生错误则返回 EOF。
int fgetc(FILE *fp);
- 函数fgets() 从 fp 所指向的输入流中读取 n-1 个字符。它会把读取的字符串复制到缓冲区 buf,并在最后追加一个 null 字符来终止字符串。如果这个函数在读取最后一个字符之前就遇到一个换行符 ‘\n’ 或文件的末尾 EOF,则只会返回读取到的字符,包括换行符。
char *fgets(char *buf, int n, FILE *fp);
- 可以使用fscanf() 函数来从文件中读取字符串,但是在遇到第一个空格和换行符时,它会停止读取。
int fscanf(FILE *fp, const char *format, ...)
示例:
#include <stdio.h>
int main() {
FILE *fp = NULL;
char buff[255];
fp = fopen("test.txt", "r");
fscanf(fp, "%s", buff);
printf("1: %s\n", buff);
fgets(buff, 255, fp);
printf("2: %s\n", buff);
/* 使用显示的强制类型转换,实际上可忽略 */
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
return 0;
}
运行结果:
1: This
2: is testing for fprintf...
3: This is testing for fputs...
首先,fscanf() 函数只读取了 This,因为它在后边遇到了一个空格。其次,调用 fgets() 读取剩余的部分,直到行尾。最后,调用 fgets() 完整地读取第二行。
参考:https://blog.csdn.net/Jmilk/article/details/105312774
C++文件操作
fstream头文件定义了三种支持文件IO的类型:
- ifstream,由istream派生而来,提供读文件功能;
- ofstream,由ostream派生而来,提供写文件功能;
- fstream,由iostream派生而来,提供读写同一文件功能;
使用示例:
//定义infile为读文件流对象,outfile为写文件流对象,不捆绑具体文件
ifstream infile; //unbound input file stream
ofstream outfile; //unbound output file stream
//捆绑具体对象
infile.open("in"); //open file named "in" in the current directory
outfile.open("out"); //open file named "out" in the current directory
outfile.close(); //close file when we are done with if
outfile.clear(); //reset state to ok
示例,Webots仿真中六足水下控制的一部分代码,将系统仿真时间持续输出到文本文件test.txt 中:
#include <fstream>
ofstream outfile("test.txt");
outfile << "开始输入" << endl;
double t = robot->getTime();
//t = t * 1000 / 32;
//t = (int) t;
outfile << t << endl;