创建并写入 C 文件

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何使用 C 编程语言创建一个新文件并向其中写入数据。FILE 数据类型用于表示 C 语言中的文件,fopen() 函数用于打开文件以进行读取、写入或追加操作。一旦文件被打开,可以使用 fprintf() 函数将数据写入文件,并在写入数据后使用 fclose() 函数关闭文件。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FileHandlingGroup(["`File Handling`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") c/FileHandlingGroup -.-> c/write_to_files("`Write To Files`") c/FileHandlingGroup -.-> c/create_files("`Create Files`") c/FileHandlingGroup -.-> c/read_files("`Read Files`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123319{{"`创建并写入 C 文件`"}} c/data_types -.-> lab-123319{{"`创建并写入 C 文件`"}} c/pointers -.-> lab-123319{{"`创建并写入 C 文件`"}} c/write_to_files -.-> lab-123319{{"`创建并写入 C 文件`"}} c/create_files -.-> lab-123319{{"`创建并写入 C 文件`"}} c/read_files -.-> lab-123319{{"`创建并写入 C 文件`"}} c/user_input -.-> lab-123319{{"`创建并写入 C 文件`"}} c/output -.-> lab-123319{{"`创建并写入 C 文件`"}} end

使用终端创建一个新的 C 程序

打开终端,并使用以下命令在 ~/project/ 目录下创建一个名为 main.c 的新 C 程序:

nano ~/project/main.c

包含必要的头文件

main.c 文件中,包含必要的头文件:

#include <stdio.h>
#include <stdlib.h>

定义变量和指针

定义变量和 FILE 类型的指针,用于保存文件及其内容:

FILE *fptr;
char name[20];
int age;
float salary;

打开文件以进行写入

使用 fopen() 函数打开文件以进行写入。如果文件不存在,将会创建该文件;否则,文件内容将被覆盖:

fptr = fopen("emp.txt", "w");
if (fptr == NULL)
{
    printf("File does not exist.\n");
    return 1;
}

将数据写入文件

提示用户输入员工的姓名、年龄和工资,并使用 fprintf() 函数将其写入文件:

printf("Enter the name:\n");
scanf("%s", name);
fprintf(fptr, "Name  = %s\n", name);

printf("Enter the age:\n");
scanf("%d", &age);
fprintf(fptr, "Age  = %d\n", age);

printf("Enter the salary:\n");
scanf("%f", &salary);
fprintf(fptr, "Salary  = %.2f\n", salary);

关闭文件

使用 fclose() 函数关闭文件:

fclose(fptr);

完成代码

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fptr;
    char name[20];
    int age;
    float salary;

    // 打开文件以进行写入
    fptr = fopen("emp.txt", "w");
    if (fptr == NULL) {
        printf("File does not exist.\n");
        return 1;
    }

    printf("Enter the name:\n");
    scanf("%s", name);
    fprintf(fptr, "Name  = %s\n", name);

    printf("Enter the age:\n");
    scanf("%d", &age);
    fprintf(fptr, "Age  = %d\n", age);

    printf("Enter the salary:\n");
    scanf("%f", &salary);
    fprintf(fptr, "Salary  = %.2f\n", salary);

    fclose(fptr);
    return 0;
}

总结

在本实验中,你学习了如何使用 C 编程语言创建一个新文件,并使用 FILEfopen()fprintf()fclose() 函数将数据写入文件。请记住,在写入数据后始终关闭文件,以避免数据丢失。

您可能感兴趣的其他 C 教程