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

Cを使用したファイルへの構造の読み取り/書き込み


fwrite()およびfread()は、Cでファイルに書き込むために使用されます。

fwrite()構文

fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

ここで

ptr-書き込まれる要素の配列へのポインタ

size-書き込まれる各要素のバイト単位のサイズ

nmemb-要素の数。各要素のサイズはバイトです

ストリーム–出力ストリームを指定するFILEオブジェクトへのポインタ

fread()構文

fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

ここで

ptr-最小サイズがsize*nmembバイトのメモリブロックへのポインタ。

size-読み取る各要素のサイズ(バイト単位)。

nmemb-要素の数。各要素のサイズはバイトです。

stream-入力ストリームを指定するFILEオブジェクトへのポインタ。

アルゴリズム

Begin
   Create a structure Student to declare variables.
   Open file to write.
   Check if any error occurs in file opening.
   Initialize the variables with data.
   If file open successfully, write struct using write method.
      Close the file for writing.
   Open the file to read.
   Check if any error occurs in file opening.
   If file open successfully, read the file using read method.
      Close the file for reading.
   Check if any error occurs.
   Print the data.
End.

これは、Cで構造体を読み取り/書き込みする例です:

サンプルコード

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
   int roll_no;
   char name[20];
};
int main () {
   FILE *of;
   of= fopen ("c1.txt", "w");
   if (of == NULL) {
      fprintf(stderr, "\nError to open the file\n");
      exit (1);
   }
   struct Student inp1 = {1, "Ram"};
   struct Student inp2 = {2, "Shyam"};
   fwrite (&inp1, sizeof(struct Student), 1, of);
   fwrite (&inp2, sizeof(struct Student), 1, of);
   if(fwrite != 0)
      printf("Contents to file written successfully !\n");
   else
      printf("Error writing file !\n");
   fclose (of);
   FILE *inf;
   struct Student inp;
   inf = fopen ("c1.txt", "r");
   if (inf == NULL) {
      fprintf(stderr, "\nError to open the file\n");
      exit (1);
   }
   while(fread(&inp, sizeof(struct Student), 1, inf))
      printf ("roll_no = %d name = %s\n", inp.roll_no, inp.name);
   fclose (inf);
}

出力

Contents to file written successfully !
roll_no = 1 name = Ram
roll_no = 2 name = Shyam

  1. Pythonopenpyxlモジュールを使用してExcelファイルの読み取りと書き込み

    Pythonは、Excelファイルを操作するためのopenpyxlモジュールを提供します。 このモジュールでは、Excelファイルの作成方法、書き込み方法、読み取り方法などを実装できます。 openpyxlモジュールをインストールするには、コマンドプロンプトでこのコマンドを記述できます pip install openpyxl シートにタイトル名を付けたい場合 サンプルコード import openpyxl my_wb = openpyxl.Workbook() my_sheet = my_wb.active my_sheet_title = my_sheet.title print

  2. Rubyでファイルを読み書きする方法(例付き)

    今日は、Rubyでファイルを読み書きして、コンテンツを抽出し、新しいファイルを作成し、必要な情報を見つける方法を学びます。 これから説明します : コンテンツ 1Rubyでファイルを読み取る方法 2Rubyでファイルに書き込む方法 3つのRubyファイルメソッド 4つのディレクトリ操作 5FileUtilsモジュールの使用方法 6まとめ 6.1関連 やってみましょう! Rubyでファイルを読み取る方法 次のようにRubyでファイルを読み取ることができます: ファイルを開く 、open メソッド。 ファイルを読む 、ファイル全体、行ごと、または特定のバイト数。 ファイルを