C 言語でファイルを作成して書き込む

CCBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C 言語で新しいファイルを作成し、そこにデータを書き込む方法を学びます。C 言語では、FILE データ型がファイルを表すために使用され、fopen() 関数がファイルを読み取り、書き込み、または追記するために開きます。ファイルが開かれると、fprintf() 関数を使用してそこにデータを書き込むことができ、データを書き込んだ後は fclose() 関数を使用してファイルを閉じます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/PointersandMemoryGroup(["Pointers and Memory"]) c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) 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()関数を使ってそのファイルにデータを書き込む方法を学びました。データを書き込んだ後は必ずファイルを閉じてデータの損失を避けることを忘れないでください。