#include<stdio.h>
//r w a r+读写 w+新建读写 a+ rb二进制 wb ab rb+ wb+ ab+
//fgetc fputc fgets fputs fscanf fprintf fread fwrite
//SEEK_SET SEEK_CUR SEEK_END
void io_c() {
FILE* fp1 = fopen("E:/1.txt", "r");
if (fp1 == 0) {
printf("文件无法打开\n");
return;
}
FILE* fp2 = fopen("E:/2.txt", "w");
//char
char c;
while (!feof(fp1)) { //是否在末尾
c = fgetc(fp1); //获取字符
putchar(c);
fputc(c, fp2);
}
fclose(fp1);
fclose(fp2);
}
void io_str() {
//str
char str[10];
FILE* fp1 = fopen("E:/1.txt", "r");
while (fgets(str, 10, fp1) != 0) {//字符串末尾,文件结束
printf("%s", str);
}
fclose(fp1);
}
void io_f() {
//str
char str[10];
FILE* fp1 = fopen("E:/3.txt", "w");
fprintf(fp1, "%s %d", "我", 100);
fclose(fp1);
char str2[10];
int a;
FILE* fp2 = fopen("E:/3.txt", "r");
while (!feof(fp2)) {
fscanf(fp2, "%s %d", str2, &a);
printf("%s %d", str2, a);
}
fclose(fp2);
}
struct student {
char name[10];
int score;
}stu = {"我",100},stu2;
void io_rw() {
//struct
FILE* fp1 = fopen("E:/4.txt", "w");
fwrite(&stu, sizeof(struct student), 1, fp1);
fclose(fp1);
FILE* fp2 = fopen("E:/4.txt", "r");
while (!feof(fp2) && fread(&stu2, sizeof(struct student), 1, fp2)) {
printf("%s %d\n", stu2.name, stu2.score);
}
fclose(fp2);
}
void io_seek() {
FILE* fp1 = fopen("E:/1.txt", "r");
if (fp1 == 0) {
printf("文件无法打开\n");
return;
}
//char
char c;
while (!feof(fp1)) { //是否在末尾
c = fgetc(fp1); //获取字符
putchar(c);
}
printf("\n指针位置: %d\n", ftell(fp1));
fseek(fp1, 5, SEEK_SET);
printf("\n指针移动后位置: %d\n", ftell(fp1));
while (!feof(fp1)) { //是否在末尾
c = fgetc(fp1); //获取字符
putchar(c);
}
fclose(fp1);
}
void io() {
//io_c();
//io_str();
//io_f();
//io_rw();
io_seek();
}
c语言-文件读写
最新推荐文章于 2025-11-23 18:41:31 发布
这篇博客详细介绍了C语言中文件的读写操作,包括使用fopen、fgetc/fputc、fgets/fputs、fprintf/fscanf进行字符和字符串的处理。同时,展示了如何利用结构体进行文件读写,并探讨了文件指针的定位技巧,如SEEK_SET、SEEK_CUR和SEEK_END。
864

被折叠的 条评论
为什么被折叠?



