Cでのファイル処理の基本
ここでは、Cでの基本的なファイル処理操作をいくつか示します。操作は次のとおりです。
- ファイルへの書き込み
- ファイルからの読み取り
- ファイルに追加する
ファイルに書き込む
コードを参照して、ファイルへの書き込み方法を理解してください
サンプルコード
#include <stdio.h>
int main() {
FILE *fp;
char *filename = "sample.txt";
char *content = "Hey there! You've successfully created a file with content in c programming language.";
/* open for writing */
fp = fopen(filename, "w");
if( fp == NULL ) {
printf("%s: failed to open. \n", filename);
return -1;
} else {
printf("%s: opened in write mode.\n", filename);
}
/* Write content to file */
fprintf(fp, "%s\n", content);
if( !fclose(fp) )
printf("%s: closed successfully.\n", filename);
return 0;
} 出力
sample.txt: opened in write mode. sample.txt: closed successfully.
2。ファイルからの読み取り
コードを使用して、ファイルからどのように読み取るかを理解します。ファイルを作成します(file_read.txt):
読み取り専用モードで、Cプログラミング言語を使用してファイルを開きました。
サンプルコード
#include <stdio.h>
int main() {
FILE *fp;
char *filename = "file_read.txt";
char ch;
/* open for writing */
fp = fopen(filename, "r");
if (fp == NULL) {
printf("%s does not exists \n", filename);
return;
} else {
printf("%s: opened in read mode.\n\n", filename);
}
while ((ch = fgetc(fp) )!= EOF) {
printf ("%c", ch);
}
if (!fclose(fp))
printf("\n%s: closed.\n", filename);
return 0;
} 出力
file_read.txt: opened in read mode. You have opened a file using C programming language, in read-only mode. file_read.txt: closed.
3。ファイルへの追加
コードを使用して、ファイルに行を追加する方法を理解してください。
ファイルを作成する(file_append.txt)
This text was already there in the file.
サンプルコード
#include <stdio.h>
int main() {
FILE *fp;
char ch;
char *filename = "file_append.txt";
char *content = "This text is appeneded later to the file, using C programming.";
/* open for writing */
fp = fopen(filename, "r");
printf("\nContents of %s -\n\n", filename);
while ((ch = fgetc(fp) )!= EOF) {
printf ("%c", ch);
}
fclose(fp);
fp = fopen(filename, "a");
/* Write content to file */
fprintf(fp, "%s\n", content);
fclose(fp);
fp = fopen(filename, "r");
printf("\nContents of %s -\n", filename);
while ((ch = fgetc(fp) )!= EOF) {
printf ("%c", ch);
}
fclose(fp);
return 0;
} 出力
Contents of file_append.txt - This text was already there in the file. Appending content to file_append.txt... Content of file_append.txt after 'append' operation is - This text was already there in the file. This text is appeneded later to the file, using C programming.
-
AIファイルとは何ですか?
知っておくべきこと AIファイルはAdobeIllustratorArtworkファイルです。 Illustratorで開くかInkscapeで無料で開きます。 Zamzarまたはそれらと同じプログラムを使用して、PNG、JPG、SVGなどに変換します。 この記事では、AIファイルとは何か、ファイルを開く方法、および他のソフトウェアと互換性を持たせるためにSVG、JPG、PDF、PNGなどの別の形式に変換する方法について説明します。 AIファイルとは何ですか? 拡張子が.AIのファイルは、AdobeのベクターグラフィックプログラムであるIllustratorによって作成されたAd
-
C++での例外処理の基本
C ++では、例外処理はランタイムエラーを処理するプロセスです。例外は、C++で実行時にスローされるイベントです。すべての例外は、std::exceptionクラスから派生します。処理可能なランタイムエラーです。例外を処理しない場合は、例外メッセージを出力してプログラムを終了します。 例外は、C ++標準では、プログラム内で使用できるクラスとして定義されています。親子クラス階層の配置を以下に示します。 C++の一般的な例外クラスは次のとおりです。 例外 説明 std ::exception これは、すべての標準C++例外の例外および親クラスです。 std ::