fgets()
多くの場合、次のようにループで呼び出されます。
FILE *fp;
char buf[260];// or char *buf, then use malloc - make index size appropriate length for anticipated line len.
fp = fopen("C:\\somedir\\card.txt", "r");
while(fgets(buf, sizeof(buf), fp)) //where sizeof(buf) is the length of
//line you anticipate reading in.
{
//do something with buf here;
//The input of fgets will be NULL as soon
//as its input fp has been fully read, then exit the loop
}
fclose(fp);
あなたの声明while((fgets(cards[i][k][j], 3, di->deckFile)) != NULL);
にはいくつかの問題があります.1つは;
最後にあります。この 1 行でループするだけで、次の行を読み取る前に、読み取られた行で何もする機会がありません。また、3
読みたい行の長さではないでしょうか。3 はカード データを保持するバッファ サイズですが、ファイルから読み取る 行は長くなります。
したがって、これらの点に加えて、コメント内の他のアイデアを検討し、指示に従って変更を加えてください。
[編集] "AS3D4C...(52 cards)" 4 行のファイルを読み取るように変更しました。4 組
のカードに十分なスペースを埋めます。これを使用
して、データを読み取る方法を確認できます。strtok (以前に使用) は、区切り文字がある場合にのみ機能し
長い文字列
の代わりに使用することをお勧めし
お役に立てれば。
(この例では [mc]alloc() を使用していないことに注意してください。
#include <ansi_c.h>
#define FILENAME "C:\\dev\\play\\cards.txt"
int main()
{
int i, j;
FILE *fp;
char buf[260];// or char *buf, then use malloc - make index size appropriate length for anticipated line len.
char *cardTok;
char cards[208][3]; //4 players, 4 decks, each card is 3 bytes (eg. [A|S|\0], they all need a null termination)
memset(cards, 0, 208*3);
fp = fopen(FILENAME, "r");
j = 0;
while(fgets(buf, sizeof(buf), fp)) //where buf len is initialized at 260
//and well over the anticipated 104/line, including \n etc.
{ //note, fgets() will read up to n-1 characters and place a \0 at the end
//but will stop reading sooner if it sees end of line.
for(i=0;i<52;i++) //i is card number
{
cards[i+j][0] = buf[2*i+0];
cards[i+j][1] = buf[2*i+1];
cards[i+j][2] = 0;
}
j+=52;
}
fclose(fp);
}
私のテキストファイルは次のようになりました:
9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD3D4SQhKD1H9H3D4SQhKDKD1H9H3D4SQhKD
6C9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD3D4SQhKD1H9H3D4SQhKDKD1H9H3D4SQh
2D9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD3D4SQhKD1H9H3D4SQhKDKD1H9H3D4SQh
3S9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H9H3D4SQhKD1H1H9H3D4SQhKD1H9H3D4SQhKD3D4SQhKD1H9H3D4SQhKDKD1H9H3D4S