#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//fprintf fscanf
void test04() {
{
FILE* f_write = fopen("./test04.txt", "w");
if (f_write == NULL) {
return;
}
//第一个参数:文件指针 第二个参数:格式化字符串
fprintf(f_write, "hello %d 年 %d 月 %d 日\n", 1999, 9, 9);
fclose(f_write);
}
{
FILE* f_read = fopen("./test04.txt", "r");
if (f_read == NULL) {
return;
}
while (!feof(f_read))
{
char buf[1024] = { 0 };
//第一个参数:文件指针 第二个参数:格式化字符串 第三个参数:文件缓冲区
fscanf(f_read,"%s",buf);//遇到空格换行
printf("%s\n",buf);
}
fclose(f_read);
}
}
//fseek ftell rewind
void test05() {
FILE* f_write;
f_write = fopen("test05.txt", "w+");//读写文件
if (f_write == NULL) {
return;
}
fprintf(f_write, "hello world\n");
/*
常量 描述
SEEK_SET 文件的开头
SEEK_CUR 文件指针的当前位置
SEEK_END 文件的末尾
*/
fseek(f_write, 0, SEEK_SET); //fseek偏移到开头,0代表偏移量
printf("%c\n", fgetc(f_write));
fseek(f_write, 2, SEEK_CUR); //fseek偏移到开头+2,2代表偏移量
printf("%c\n", fgetc(f_write));
fseek(f_write, -3, SEEK_END); //fseek偏移到末尾-3,-3代表偏移量
printf("%c\n", fgetc(f_write));//注意d的位置在"hello world\n"有换行的情况下是末尾-3位置
fseek(f_write, 0, SEEK_END);
printf("%d\n",ftell(f_write));//ftell获取位置,单位(字节),其中\n占用两个字节
rewind(f_write);//rewind将光标置到开头
printf("%c\n", fgetc(f_write));
fclose(f_write);
}
int main(int argc, char* argv[])
{
//test04();
//test05();
system("pause");
return EXIT_SUCCESS;
}
C语言-文件读写回顾.下
于 2024-08-10 10:55:00 首次发布