なぜCプログラミング言語でファイルが必要なのですか?
ファイルはレコードのコレクションです(または)データが永続的に保存されるハードディスク上の場所です。 Cコマンドを使用して、さまざまな方法でファイルにアクセスします。
C言語のファイルの必要性
-
プログラムが終了するとデータ全体が失われ、ファイルに保存すると、プログラムが終了してもデータが保持されます。
-
大量のデータを入力したい場合、通常、すべてのデータを入力するのに時間がかかります。
-
すべてのデータを含むファイルがある場合は、Cのいくつかのコマンドを使用して、ファイルの内容に簡単にアクセスできます。
-
変更を加えることなく、あるコンピューターから別のコンピューターにデータを簡単に移動できます。
ファイルの操作
C言語のファイルで実行できる操作は次のとおりです-
- ファイルに名前を付ける。
- ファイルを開きます。
- ファイルからの読み取り。
- ファイルへの書き込み。
- ファイルを閉じます。
構文
ファイルを開いて名前を付けるの構文 次のとおりです-
FILE *File pointer;
たとえば、FILE * fptr;
File pointer = fopen ("File name”, "mode”); たとえば、fptr =fopen( "sample.txt"、 "r")
FILE *fp;
fp = fopen ("sample.txt”, "w”); ファイルから読み取るの構文 次のとおりです-
int fgetc( FILE * fp );// read a single character from a file
ファイルへの書き込みの構文 次のとおりです-
int fputc( int c, FILE *fp ); // write individual characters to a stream
例
以下は、ファイルをデモンストレーションするためのCプログラムです-
#include<stdio.h>
void main(){
//Declaring File//
FILE *femp;
char empname[50];
int empnum;
float empsal;
char temp;
//Opening File and writing into it//
femp=fopen("Employee Details.txt","w");
//Writing User I/p into the file//
printf("Enter the name of employee : ");
gets(empname);
//scanf("%c",&temp);
printf("Enter the number of employee : ");
scanf("%d",&empnum);
printf("Enter the salary of employee : ");
scanf("%f",&empsal);
//Writing User I/p into the file//
fprintf(femp,"%s\n",empname);
fprintf(femp,"%d\n",empnum);
fprintf(femp,"%f\n",empsal);
//Closing the file//
fclose(femp);
//Opening File and reading from it//
femp=fopen("Employee Details.txt","r");
//Reading O/p from the file//
fscanf(femp,"%s",empname);
//fscanf(femp,"%d",&empnum);
//fscanf(femp,"%f",&empsal);
//Printing O/p//
printf("employee name is : %s\n",empname);
printf("employee number is : %d\n",empnum);
printf("employee salary is : %f\n",empsal);
//Closing File//
fclose(femp);
} 出力
上記のプログラムを実行すると、次の結果が得られます-
Enter the name of employee : Pinky Enter the number of employee : 20 Enter the salary of employee : 5000 employee name is : Pinky employee number is : 20 employee salary is : 5000.000000
-
ファイルのputc()およびgetc()関数をC言語で説明する
ファイルはレコードのコレクションであるか、データが永続的に保存されるハードディスク上の場所です。 ファイルの操作 Cプログラミング言語でのファイルの操作は次のとおりです- ファイルの命名 ファイルを開く ファイルからの読み取り ファイルへの書き込み ファイルを閉じる 構文 ファイルを開くための構文は次のとおりです- FILE *File pointer; たとえば、FILE * fptr; ファイルに名前を付けるための構文は次のとおりです- File pointer = fopen ("File name", "mode"); たとえば、
-
C言語の高レベルI/O関数とは何ですか?
I / Oは、C言語の入出力関数を指します。 高レベルI/O これらは人間が簡単に理解できます 利点は移植性です。 低レベルI/O これらはコンピューターで簡単に理解できます。 利点は、実行時間が短いことです。 欠点は、移植性がないことです。 高レベルのI/O機能 高レベルの入出力(I / O)機能について以下に説明します- 関数 説明 fprintf() データをファイルに書き込む fscanf() ファイルからデータを読み取る putc()/ fputc() ファイルに文字を書き込む getc()/ fgetc() ファイルから文字を読み取る