Cプログラミング
 Computer >> コンピューター >  >> プログラミング >> Cプログラミング

Cプログラムでファイルの終わり(EOF)を説明する


ファイルの終わり(EOF)は、入力の終わりを示します。

テキストを入力した後、ctrl + Zを押すと、テキストは終了します。つまり、ファイルが最後に到達したことを示し、何も読み取ることができません。

アルゴリズム

EOFについては、以下のアルゴリズムを参照してください。

Step 1: Open file in write mode.
Step 2: Until character reaches end of the file, write each character in filepointer.
Step 3: Close file.
Step 4: Again open file in read mode.
Step 5: Reading the character from file until fp equals to EOF.
Step 5: Print character on console.
Step 6: Close file.

以下は、ファイルの終わり(EOF)のCプログラムです-

#include <stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w"); //open the file in write mode
   printf("enter the text then press cntrl Z:\n");
   while((ch = getchar())!=EOF) //reading char by char until it equals to EOF{
      i.e. when u press ctrlZ the while loop terminates
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF) //reading the character from file until fp equals to EOF{
      putchar(ch);
   }
   fclose(fp);
   return 0;
}

出力

上記のプログラムを実行すると、次の結果が得られます-

enter the text then press cntrl Z:
This is the EOF demonstration example
if your text typing is over press cntrlZ
^Z
text on the file:
This is the EOF demonstration example
if your text typing is over press cntrlZ

  1. C言語のループ制御ステートメントとは何ですか?フローチャートとプログラムで説明する

    ループ制御ステートメントは、一連のステートメントを繰り返すために使用されます。それらは次のとおりです- forループ whileループ do-whileループ forループ 構文は次のとおりです- for (initialization ; condition ; increment / decrement){    body of the loop } フローチャート ループのフローチャートは次のとおりです- 初期化は通常、ループ制御変数を設定するために使用される割り当てステートメントです。 条件は、ループがいつ終了するかを決定する関係式です。

  2. Cプログラムのリンクリストの最後からn番目のノードのプログラム

    n個のノードがある場合、タスクはリンクリストの最後からn番目のノードを印刷することです。プログラムは、リスト内のノードの順序を変更してはなりません。代わりに、リンクリストの最後からn番目のノードのみを出力する必要があります。 例 Input -: 10 20 30 40 50 60    N=3 Output -: 40 上記の例では、最初のノードからカウントnノードまでのノードがトラバースされます(10、20、30、40、50、60)。したがって、最後から3番目のノードは40です。 リスト全体をトラバースする代わりに、この効率的なアプローチに従うことができます-