File operation (standard I / O)

Compiler environment: Dev c ++ compiler
programming language: c language

File Open Mode:

1 - r (read): Read
2 - w (write): Write
3 - a (append): Append
4 - t (text): Text File
5 - b (banary): binaries
6 - +: read and write

File format is divided into: text files and binary files
read mode of file: sequential read and random read

First set: fputc and fgetc function (reading in characters)

  • fgetc function

Int fgetc (FILE * fp): read a character from the specified disk file in
return EOF (EOF when reading a character from the specified file and returns to the characters successfully read, read to the end of the file or read failed a macro is usually -1)
file location: a location within the file pointer, used to point to the current read position to the first byte just opened a file, using a plurality of characters can be continuously read fgetc , the position of the pointer is just a flag that indicates the position automatically by the system, the user is hidden

#include<stdio.h>
int main()
{
	char c;
    FILE *fp;
    if( (fp=fopen("data.txt", "r")) == NULL ){
        puts("Fail to open file!");
        exit(0);
    }
    while((c=fgetc(fp))!=EOF){
		printf("%c",c);
	}
	printf("读取完毕!\n");
    fclose(fp);
    return 0;
}

Run shot:
Here Insert Picture Description

  • fputc function

Write a character to the specified disk file: int foutc (CH int, FILE * fp)
CH character written, fp is the file pointer, successfully returns the character written, failed to return EOF

#include<stdio.h>
int main()
{
	char c;
    FILE *fp;
    if( (fp=fopen("data.txt", "aw")) == NULL ){
        puts("Fail to open file!");
        exit(0);
    }
    while((c=getchar())!='\n'){
		fputc(c,fp);
	}
	printf("写入完毕!\n");
    fclose(fp);
    return 0;
}

Run shot:
Here Insert Picture Description

Second set: fputs and function fgets (string read)

  • fgets function

从指定磁盘文件中读取一个字符串:char *fgets(char *str,int n,FILE *fp)
str为字符数组,n为要读取的字符数目,fp为文件指针
返回值:成功返回字符数组首地址,失败返回NULL
读取到的字符串会在末尾自动添加’\0’,n个字符包括’\0’,实际读取了n-1个字符

#include<stdio.h>
#define num 100
int main()
{
	char str[num];
    FILE *fp;
    if( (fp=fopen("data.txt", "r")) == NULL ){
        puts("Fail to open file!");
        exit(0);
    }
    while((fgets(str,num,fp))!=NULL){
		printf("%s\n",str);
	}
	printf("读取完毕!\n");
    fclose(fp);
    return 0;
}

运行截图:
Here Insert Picture Description

  • fputs函数

向指定磁盘文件写入一个字符串:int fputs(char *str,FILE *fp)
str为要写入的字符串,fp为文件指针
返回值:成功返回非负数,失败返回EOF

#include<stdio.h>
int main()
{
	char str[20]="我爱中国123abc";
    FILE *fp;
    if( (fp=fopen("data.txt", "aw")) == NULL ){
        puts("Fail to open file!");
        exit(0);
    }
    fputs(str,fp);
	printf("写入完毕!\n");
    fclose(fp);
    return 0;
}

运行截图:
Here Insert Picture Description
第三组:fread和fwrite函数(数据块形式读取)

  • fread函数

从指定磁盘文件中读取块数据:
size_t fread ( void *ptr, size_t size, size_t count, FILE *fp )

  • fwrite函数

向指定磁盘文件中写入块数据:
size_t fwrite ( void * ptr, size_t size, size_t count, FILE *fp )

ptr:块数据指针
size:每个数据块的字节数
count:读写的数据块的数量
fp:文件指针
返回值:成功返回读写的块数量count,失败返回值小于count

#include<stdio.h>
struct stu{
    char name[10];
    int num; 
    int age;  
    float score;  
}usa[2], usb[2];
int main(){
    FILE *fp;
    int i;
    if( (fp=fopen("data.txt", "wb+")) == NULL ){
        puts("Fail to open file!");
        exit(0);
    }
    printf("Input data:\n");
    for(i=0; i<2; i++){
        scanf("%s %d %d %f",usa[i].name, &usa[i].num,&usa[i].age, &usa[i].score);
    }
    fwrite(usa, sizeof(struct stu), 2, fp);
    rewind(fp);
    fread(usb, sizeof(struct stu), 2, fp);
    for(i=0; i<2; i++){
        printf("%s  %d  %d  %f\n", usb[i].name, usb[i].num, usb[i].age, usb[i].score);
    }
    fclose(fp);
    return 0;
}

运行截图:
Here Insert Picture Description
第四组:fscanf和fprintf函数(格式化形式读取)

从指定的磁盘文件中读取格式字符: int fscanf(FILE *fp,char *format, … )
向指定的磁盘文件中写入格式字符: int fprintf(FILE *fp,char *format, … )
fp:文件指针
format:格式控制字符串
… :表示参数列表
返回值:成功返回写入/读取的字符个数,失败返回负数

#include<stdio.h>
#define num 5
struct stu{
    char name[10];
    int number;
    int age;
    float score;
} usa[num], usb[num];
int main(){
    FILE *fp;
    int i;
    if( (fp=fopen("data.txt","a+")) == NULL ){
        puts("Fail to open file!");
        exit(0);
    }
    printf("Input data:\n");
    for(i=0; i<num; i++){
        scanf("%s %d %d %f", usa[i].name, &usa[i].number, &usa[i].age, &usa[i].score);   
    }
    for(i=0; i<num; i++){
        fprintf(fp,"姓名: %s 学好: %d 年龄: %d 成绩: %f\n", usa[i].name, usa[i].number, usa[i].age, usa[i].score);   
    }
    rewind(fp);
    for(i=0; i<num; i++){
        fscanf(fp, "姓名: %s 学好: %d 年龄: %d 成绩: %f\n", usb[i].name, &usb[i].number, &usb[i].age, &usb[i].score);
    }
    for(i=0; i<num; i++){
        printf("%s  %d  %d  %f\n", usb[i].name, usb[i].number, usb[i].age, usb[i].score);
    }
    fclose(fp);
    return 0;
}

运行截图:
Here Insert Picture Description

第五组:rewind和fseek函数(随机读写方式)

将位置指针移动到文件开头:void rewind(FILE *fp)
将位置指针移动到任意位置:int fseek(FILE *fp,long offset,int origin)
fp:文件指针
offset:偏移量
origin:相对于offset的起始位置
文件开头:SEEK_SET:0
当前位置:SEEK_CUR:1
文件末尾:SEEK_END:2
(fssek()一般用于二进制文件,文本文件中位置可能不准确)

#include<stdio.h>
#define num 3
struct stu{
    char name[10]; 
    int number;  
    int age; 
    float score;  
}usr[num], user;
int main(){
    FILE *fp;
    int i;
    if( (fp=fopen("data.txt", "ab+")) == NULL ){
        printf("Cannot open file, press any key to exit!\n");
        exit(1);
    }
    printf("Input data:\n");
    for(i=0; i<num; i++){
        scanf("%s %d %d %f", usr[i].name, &usr[i].number, &usr[i].age, &usr[i].score);
    }
    fwrite(usr, sizeof(struct stu), num, fp);  
    fseek(fp, sizeof(struct stu), SEEK_SET);  
    fread(&user, sizeof(struct stu), 1, fp); 
    printf("%s  %d  %d %f\n", user.name, user.number, user.age, user.score);
    fclose(fp);
    return 0;
}

运行截图:
Here Insert Picture Description

总结

总体来说文件的操作:
1、打开文件设备(fopen)
2、确定程序使用的数据(字符、字符串、块数据、格式化数据)
3、使用函数时要配对使用(选择一对函数)
4、读取/写入操作
5、关闭文件设备(fclose)

Binary file is written to disk in binary format, general editor opens distortion
when a large number of read and write file operation, the file pointer location must be clear, as well as writing and reading of the format must correspond to
the general procedure, the file acting as a database, write and read operations on the information in the database, because the program is running in memory after the program is running, all data is lost, written to disk / hard disk file after the program easy to use

c language management system:
general use the fscanf () and fprintf () function to read and write the file
can be directly read or write monolithic structure information, written information can also be viewed

Guess you like

Origin blog.csdn.net/qq_42856154/article/details/93225821