0

我对 C 很陌生,我在 C 中遇到了一个问题:我想编写一个程序来读取 txt 文件并将其内容写入char[50][50].

要读取我使用的文件,fopen但我不知道如何将其写入数组。解决这个问题的好方法是什么?

4

3 回答 3

2

如果 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;
}
于 2012-05-20T11:28:56.743 回答
1

编辑:@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;
}

确实应该有一些代码来检查输入文件是否符合您的期望,否则可能会发生奇怪的事情。

于 2012-05-20T10:34:32.250 回答
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 循环,在其中测试读取的最后一个字符是否不是文件的结尾。我希望你能用这段代码填充你的数组。

于 2012-05-20T10:04:06.003 回答