相关函数
// 打开文件
FILE *fopen( const char * filename, const char * mode );
// 关闭文件
int fclose( FILE *fp );
// 写入文件
int fputc( int c, FILE *fp );
int fputs( const char *s, FILE *fp );
// 读取文件
int fgetc( FILE * fp );
char *fgets( char *buf, int n, FILE *fp );
打开文件模式
模式 | 描述 |
---|---|
r | 打开一个已有的文本文件,允许读取文件。 |
w | 打开一个文本文件,允许写入文件。 如果文件不存在,则会创建一个新文件。如果有,则从文件的开头写入内容。 |
a | 打开一个文本文件,以追加模式写入文件。 如果文件不存在,则会创建一个新文件。如果有,则在已有文件中追加内容。 |
r+ | 打开一个文本文件,允许读写文件。 |
w+ | 打开一个文本文件,允许读写文件。 如果文件已存在,则文件会被截断为零长度,如果文件不存在,则会创建一个新文件。 |
a+ | 打开一个文本文件,允许读写文件。 如果文件不存在,则会创建一个新文件。读取会从文件的开头开始,写入则只能是追加模式。 |
动态读入int数组
#include <stdio.h>
#include <stdlib.h>
// 动态读入文件中的 int 数组
int main() {
FILE *fp = fopen("/Users/shuai/CLionProjects/C/data.txt", "r"); // 文件路径是绝对路径
if (fp == NULL) { // fp是个指针对象,如果打开失败指向默认值NULL
printf("open error\n");
exit(0);
}
// 计算文件中数字总个数
int x;
int len = 0;
while (!feof(fp)) {
fscanf(fp, "%d%*[^0123456789]", &x); // 从文件中只读出数字
len++;
}
rewind(fp); // 指针回到文首
// 正式读入数据
int a[len];
for (int i = 0; i < len; ++i) {
fscanf(fp, "%d%*[^0123456789]", &a[i]);
printf("%d\t", a[i]);
}
fclose(fp); // 关闭文件
return 0;
}
data.txt
1 Hello 2 World
3 I
4 can
5 play
输出
1 2 3 4 5
动态读入string数组
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("/Users/shuai/CLionProjects/C/data.txt", "r"); // 文件路径是绝对路径
if (fp == NULL) { // fp是个指针对象,如果打开失败指向默认值NULL
printf("open error\n");
exit(0);
}
// 计算string的个数
int len = 0;
char buf[20];
while (!feof(fp)) {
fscanf(fp, "%s", buf);
len++;
}
rewind(fp);
// char *words[len]; // 这样初始化是错误的,没有分配空间
char words[len][20];
int i=0;
while (!feof(fp)) {
fscanf(fp, "%s", words[i]);
i++;
}
for (int j = 0; j < len; ++j) {
printf("%s\n", words[j]);
}
fclose(fp); // 关闭文件
return 0;
}
data.txt
where are you now?
输出
where
are
you
now?
写入文件
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/Users/shuai/CLionProjects/C/data.txt", "w+"); // 这种方式会覆盖掉原有的数据
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
data.txt
This is testing for fprintf...
This is testing for fputs...