Leitura e gravação de arquivos em linguagem C

1. Ler e gravar arquivos txt

Esse código pode gravar uma string em um arquivo e ler uma string de um arquivo e enviá-la para o console.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int main()
{
    FILE *fp;
    char str[100];
    // 写入文件
    fp = fopen("test.txt", "w");
    fprintf(fp, "This is a test.\n");
    fputs("Hello, World!", fp);
    fclose(fp);
    // 读取文件
    fp = fopen("test.txt", "r");
    while (fgets(str, 100, fp) != NULL)
    {
        printf("%s", str);
    }
    fclose(fp);
    return 0;
}

2. Ler e gravar arquivos binários

Primeiro abra um arquivo chamado "data.bin", escreva a string "Hello, world!" no arquivo usando a função fwrite() e então feche o arquivo. Em seguida, abra o arquivo novamente, use a função fread() para ler os dados do arquivo no buffer e, finalmente, envie o conteúdo do buffer.
#include <stdio.h>
int main() {
    FILE *fp;
    char buffer[100];
    // 写入二进制文件
    fp = fopen("data.bin", "wb");
    fwrite("Hello, world!", sizeof(char), 13, fp);
    fclose(fp);
    // 读取二进制文件
    fp = fopen("data.bin", "rb");
    fread(buffer, sizeof(char), 13, fp);
    fclose(fp);
    printf("%s\n", buffer);
    return 0;
}

3. Estrutura de leitura e gravação

É definida uma estrutura chamada aluno , que contém o nome, idade e série do aluno. Na função principal , primeiro criamos uma variável stu do tipo aluno e inicializamos seu valor. Em seguida, usamos a função fopen para abrir um arquivo chamado student.dat e usamos a função fwrite para escrever stu no arquivo. Em seguida, usamos a função fopen para abrir o arquivo novamente e usamos a função fread para ler os dados do arquivo na variável stu . Por fim, imprimimos os valores na variável stu , que é o nome, idade e série do aluno.
Observe que este código é apenas um exemplo e precisa ser modificado e aprimorado de acordo com as necessidades específicas das aplicações reais.

básico

#include <stdio.h>
struct student
{
    char name[20];
    int age;
    float score;
}
;
int main() {
    struct student stu =
    {
        "Tom", 18, 90.5
    }
    ;
    FILE *fp;
    // 写入结构体数据到文件
    fp = fopen("student.dat", "wb");
    fwrite(&stu, sizeof(struct student), 1, fp);
    fclose(fp);
    // 从文件中读取结构体数据
    fp = fopen("student.dat", "rb");
    fread(&stu, sizeof(struct student), 1, fp);
    printf("Name: %s\nAge: %d\nScore: %.1f\n", stu.name, stu.age, stu.score);
    fclose(fp);
    return 0;
}

Melhoria

#include <stdio.h>
typedef struct
{
    int id;
    char name[20];
    float score;
}Student;

int main()
{
    Student stu =
    {
        1, "Tom", 89.5
    };
    FILE *fp = fopen("student.dat", "wb");
    if (fp == NULL)
    {
        printf("Failed to open file.\n");
        return 1;
    }
    fwrite(&stu, sizeof(Student), 1, fp);
    fclose(fp);
    fp = fopen("student.dat", "rb");
    if (fp == NULL)
    {
        printf("Failed to open file.\n");
        return 1;
    }
    fread(&stu, sizeof(Student), 1, fp);
    printf("ID: %d\nName: %s\nScore: %.1f\n", stu.id, stu.name, stu.score);
    fclose(fp);
    return 0;
}

Acho que você gosta

Origin blog.csdn.net/qq_42815643/article/details/129539716
Recomendado
Clasificación