私はCにかなり慣れていないので、Cでここに問題があります.txtファイルを読み取り、コンテンツを.txtファイルに書き込むプログラムを書きたいですchar[50][50]
。
私が使用したファイルを読み取るためfopen
に、これを配列に書き込む方法がわかりません。これを解決する良い方法は何ですか?
私はCにかなり慣れていないので、Cでここに問題があります.txtファイルを読み取り、コンテンツを.txtファイルに書き込むプログラムを書きたいですchar[50][50]
。
私が使用したファイルを読み取るためfopen
に、これを配列に書き込む方法がわかりません。これを解決する良い方法は何ですか?
特定のサイズのファイルから読み取るだけであれば、使いやすい fread です。
例えば
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char data[50][50];
int count;
if(NULL==(fp=fopen("data.txt","r"))){
perror("file not open\n");
exit(EXIT_FAILURE);
}
count=fread(&data[0][0], sizeof(char), 50*50, fp);
fclose(fp);
{ //input check
int i;
char *p = &data[0][0];
for(i=0;i<count;++i)
putchar(*p++);
}
return 0;
}
編集:@BLUEPIXYの答えは、このアプローチよりもはるかに優れています。
この特定の例に適応した@Hiddeのコード:
// Include the standard input / output files.
// We'll need these for opening our file
#include <stdio.h>
int main ()
{
// A pointer to point to the memory containing the file data:
FILE * pFile;
// Open the file itself:
pFile=fopen ("250.txt","r");
// Check that we opened the file successfully:
if (pFile==NULL)
{
perror ("Error opening file");
}
else
{
// The file is open so we can read its contents.
// Lets just assume its got 50*50=250 chars in.
// Initialise an array to hold our results:
char array[50][50];
int row, col;
for (row = 0; row < 50; row++)
{
for (col = 0; col < 50; col++)
{
// Store the next char from our file in our array:
array[row][col] = fgetc (pFile);
}
}
// Close the file
fclose (pFile);
// Demonstrate that we've succeeded:
for (row = 0; row < 50; row++)
{
for (col = 0; col < 50; col++)
{
printf("%c", array[row][col]);
}
printf("\n");
}
}
// Return 0 indictaes success
return 0;
}
実際には、入力ファイルが期待どおりであることを確認するコードが必要です。そうしないと、奇妙なことが起こる可能性があります。
/* fgetc example: money counter */
#include <stdio.h>
int main ()
{
FILE * pFile;
int c;
int n = 0;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
do {
c = fgetc (pFile);
if (c == '$') n++;
} while (c != EOF);
fclose (pFile);
printf ("The file contains %d dollar sign characters ($).\n",n);
}
return 0;
}
CPlusPlus.comからコピーされました。を使用してファイルを読み取ることができますfgetc(FILE* )
。最後に読み取った文字がファイルの終わりではないかどうかをテストするwhileループを作成します。このコードで配列を埋めることができるといいのですが。