读取文件
1059字约4分钟
2025-05-28
存文本文件:Windows记事本能打开的文件就是存文本文件
读取文件
fopen的几种模式 | 描述 |
---|---|
r | 只读模式 |
w | 只写模式 细节1:文件不存在,创建新文件 细节2:文件已存在,清空文件 |
a | 追加写入模式 细节1:文件不存在,创建新文件 细节2:文件已存在,不清空文件,续写 |
rb | 只读模式(读取二进制文件,例如:图片、视频之类的) |
wb | 只写模式(操作二进制文件) 细节1:文件不存在,创建新文件 细节2:文件以存在,清空文件 |
ab | 追加写入模式(操作二进制文件) 细节1:文件不存在,创建新文件 细节2:文件已存在,清空文件 |
fopen("file", "r+")是以读写方式打开一个文本文件,文件必须已存在,
并且既可以读取文件原有内容,也可以对文件进行修改操作,
符合 “打开一个已存在的非空文件用于修改” 的要求
/*
打开文件:fopen
写出数据:fgetc 一次读一个字符,读不到返回 -1
fgets 一次读一行,读不到返回 null
fread 一次读多个
关闭文件:fclose
*/
测试文件内容
Hello,World! 你好,世界!
读取单个字符
// 文件路径
// fopen("文件路径", "模式");
FILE *file = fopen("C:\\Users\\Windows\\Pictures\\file\\ceshi.txt", "r");
// 读取字符
int c;
// fgetc(file) 读取file中的字符
while ((c = fgetc(file)) != -1)
{
// char c = fgetc(file);
printf("%c", c);
}
// 关闭文件,释放内存
fclose(file);
读取一行文字
// 文件路径
FILE *file = fopen("C:\\Users\\Windows\\Pictures\\file\\ceshi.txt", "r");
// 读取一行文字
char zi[1024];
char *str;
while ((str = fgets(zi, 1024, file)) != NULL)
{
// fgets(zi, 1024, file);
// zi 将file中的值传到 zi 数组中;1024 表示读取一行字符的最大长度;file表示文件路径
printf("%s\n", str);
}
// char *str1 = fgets(zi, 1024, file);
// printf("%s\n", str1);
// 关闭文件,释放内存
fclose(file);
读取整个文件
// 文件路径
FILE *file = fopen("C:\\Users\\Windows\\Pictures\\file\\ceshi.txt", "r");
char ch[1024];
// 当没有数据读取时,返回 0
int n;
// ch 将file中的值传到 ch 数组中; 1 表示每个字符的占用大小;
// 1024 表示读取一行字符的最大长度;file表示文件路径
while ((n = fread(ch, 1, 1024, file)) != 0)
{
printf("%d", n);
printf("%s", ch);
}
// 关闭文件,释放内存
fclose(file);
写入数据
// fputc 写入字符
fputc('a', file);
// fputs 写入字符串
fputs("\nHello,世界!", file);
// fwrite 一次写入多个值,返回写入值的个数
fwrite(str, 1, len, file);
写入字符
// 文件路径
FILE *file = fopen("C:\\Users\\Windows\\Pictures\\file\\a.txt", "w");
// fputc 写入字符
// 写入成功,则返回写入的值
int c = fputc('a', file);
// 这里的97表示的是ASCII码
int c1 = fputc(99, file);
printf("%d\n", c);
// 关闭文件,释放内存
fclose(file);
写入字符串
// 文件路径
FILE *file = fopen("C:\\Users\\Windows\\Pictures\\file\\a.txt", "w");
// fputs 写入字符串
// 写入成功则返回一个非负数
// 如果写入失败,则返回一个EOF的错误
int n = fputs("\nHello,世界!", file);
printf("%d\n", n);
// 关闭文件,释放内存
fclose(file);
写入多个字符
// 文件路径
FILE *file = fopen("C:\\Users\\Windows\\Pictures\\file\\a.txt", "w");
// fwrite 一次写入多个值,返回写入值的个数
char str[] = {99, 'a', 111, 'k'};
int len = sizeof(str) / sizeof(char);
int n1 = fwrite(str, 1, len, file);
printf("%d", n1);
// 关闭文件,释放内存
fclose(file);
拷贝文件
#include <stdio.h>
void main()
{
// 读取的文件
FILE *file1 = fopen("C:\\Users\\Windows\\Pictures\\file\\c.pdf", "rb");
// 将读取的文件复制到何处
FILE *file2 = fopen("C:\\Users\\Windows\\Pictures\\file\\copy.pdf", "wb");
// 定义一个存放数据的数组
char cun[1024];
// 统计写入值的个数
int n;
// 将读取的文件传到数组中
while ((n = fread(cun, 1, 1024, file1)) != 0)
{
// 将数组中的文件复制到对应的位置上去
fwrite(cun, 1, n, file2);
}
// 关闭文件,释放内存
fclose(file1);
fclose(file2);
}