1.打开文件:fopen()
文件的打开操作指定的文件在内存上分配一个file结构区,并以指针返回,可以对这个指针来完成对文件的读写操作。
函数参数:文件名,操作方式;
操作方式:r—只读打开; w—只写打开; a—指针指向文件末尾打开,在后面增加内容; rb—只读打开一个二进制文件; wb—只写打开一个二进制文件; ab—打开一个二进制文件并指向文件末尾; r+—读写打开一个已有的文件; w+—读写打开一个新建的文件; a+—读写打开一个文件并指向文件末尾; rb+—读写打开二进制文件; wb+—读写打开并新建的二进制文件; ab+—读写打开一个二进制文件并指向文件末尾。
只读打开不存在的文件,打开失败,返回空指针。feof(file)—读取完 文件结束
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void main()
{
FILE *file;
char*filename = "1.txt";
file = fopen(filename, "r+");
if (file == NULL)
printf("open error\n");
fclose(file);
system("pause");
}
2.关闭文件fclose()
关闭文件操作后写入的内容才会保存到文件里,所以对文件操作后关闭文件是必要的;关闭所有打开的文件fcloseall();同时返回关闭的文件数。
3.读写文件
3.1 按字符读写:
fgetc(file) 从文件读取出一个字符
fputc(i,file) 把字符i写入文件
for (int i = 0; i < strlen(a); i++)
fputc(a[i], fp);
while (!feof(fp))
{
char temp = fgetc(fp);
printf("%c", temp);
}
fgets(_a[],n,file) 按行的读取出来
fputs("hello",file) 写入字符串
char buf[1024];
while (!feof(fp))
{
fgets(buf, 1024, fp);
printf("%s", buf);
}
3.2 按块的读写
写入一个结构体数组:
typedef struct teacher{
int age;
char name[64];
}teacher;
void main()
{
FILE *fp = NULL;
char *filename = "2.txt";
teacher array[3];
for (int i = 0; i < 3; i++){
sprintf(array[i].name, "%s%d", "link",i);
array[i].age = i + 31;
}
//写入
fp = fopen(filename, "wb");
if (fp == NULL){
printf("open err\n");
}
printf("open success\n");
for (int i = 0; i < 3; i++){
//fwrite(_In_reads_bytes_(_Size*_Count) const void * _Str, _In_ size_t _Size, _In_ size_t _Count, _Inout_ FILE * _File);
fwrite(&array[i],sizeof(teacher),1,fp);
}
if (fp != NULL)
fclose(fp);
teacher temp[3];
//读取
fp = fopen(filename, "r+");
if (fp == NULL){
printf("open err\n");
}
printf("open success\n");
for (int i = 0; i < 3; i++){
fread(&temp[i],sizeof(teacher),1,fp);
}
for (int i = 0; i < 3; i++){
printf("name:%s,age:%d",temp[i].name,temp[i].age);
}
if (fp != NULL)
fclose(fp);
system("pause");
}
fwrite(): fread():
可以看到函数定义:fwrite(_In_reads_bytes_(_Size*_Count) const void * _Str, _In_ size_t _Size, _In_ size_t _Count, _Inout_ FILE * _File);
fread(_Out_writes_bytes_(_ElementSize*_Count) void * _DstBuf, _In_ size_t _ElementSize, _In_ size_t _Count, _Inout_ FILE * _File);
都是四个参数,分别是内存开始位置、块大小、写入次数、文件。