#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//fputc fgetc
void test01() {
{
FILE* f_write = fopen("./test01.txt", "w+");
if (f_write == NULL) {
return;
}
char buf[] = "this is first test";
for (int i = 0; i < strlen(buf); ++i) {
//第一个参数:要写入的字符 第二个参数:文件指针
fputc(buf[i], f_write);
}
fclose(f_write);
}
{
FILE* f_read = fopen("./test01.txt", "r");
if (f_read == NULL) {
return;
}
char ch;
//第一个参数:文件指针
while ((ch = fgetc(f_read)) != EOF/*EOF End Of File*/) {
printf("%c",ch);
}
fclose(f_read);
}
}
//fputs fgets
void test02() {
{
FILE* f_write = fopen("./test02.txt", "w+");
if (f_write == NULL) {
return;
}
char* buf[] = {
"11111111\n",
"22222222\n",
"33333333\n",
"44444444\n"
};
for (int i = 0; i < sizeof(buf) / sizeof(buf[0]); ++i) {
//第一个参数:要写入的字符串 第二个参数:文件指针
fputs(buf[i], f_write);
}
fclose(f_write);
}
{
FILE* f_read = fopen("./test02.txt", "r");
if (f_read == NULL) {
return;
}
char ch;
//EOF End Of File
while (!feof(f_read)) {
char buf[1024] = { 0 };
//第一个参数:目标缓冲区 第二个参数:缓冲区大小 第三个参数:文件指针
fgets(buf, 1024, f_read);
printf("%s",buf);
}
fclose(f_read);
}
}
struct Hero
{
char name[64];
int age;
};
//fwrite fread
void test03() {
{
FILE* f_write = fopen("./test03.txt", "wb");
if (f_write == NULL) {
return;
}
struct Hero heros[] =
{
{"张三",18},
{"李四",20},
{"王五",33},
{"赵六",54}
};
for (int i = 0; i < sizeof(heros)/sizeof(heros[0]); ++i) {
//第一个参数:数据地址 第二个参数:块大小 第三个参数:块个数 第四个参数:文件指针
fwrite(&heros[i], sizeof(struct Hero), 1, f_write);
}
fclose(f_write);
}
{
FILE* f_read = fopen("./test03.txt", "rb");
if (f_read == NULL) {
return;
}
struct Hero temp[4];
//第一个参数:数据地址 第二个参数:块大小 第三个参数:块个数 第四个参数:文件指针
fread(&temp, sizeof(struct Hero), 4, f_read);
for (int i = 0; i < sizeof(temp) / sizeof(temp[0]); ++i) {
printf("name:%s age:%d\n",temp[i].name,temp[i].age);
}
fclose(f_read);
}
}
int main(int argc, char* argv[])
{
//test01();
//test02();
//test03();
system("pause");
return EXIT_SUCCESS;
}
C语言-文件读写回顾.上
于 2024-08-10 10:07:09 首次发布