2012-05-20 2 views
0

저는 C에서 매우 익숙합니다. 여기에서 C로 문제가 있습니다 : txt 파일을 읽고 내용을 쓰는 프로그램을 작성하고 싶습니다. char[50][50].C에서 txt 파일에서 char [] []를 만드는 방법은 무엇입니까?

파일을 읽으려는 경우 fopen을 사용했지만 배열에이 파일을 쓰는 방법을 모릅니다. 이것을 해결하는 좋은 방법은 무엇입니까?

+2

파일의 모양은 어떻습니까? "행"을 정의하는 것은 무엇입니까? – cnicutar

+2

그리고 무엇을 시도 했습니까? – Mat

+0

txt는 임의로 "X"로 채워지며 나중에 시작점을 정의해야합니다. 나는 아직 익숙하지 않았기 때문에 아무것도 시도하지 않았다. 그냥 구글에 물었다. – Seph

답변

1

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

은 정말 몇 가지 코드가 다른 이상한 일들이 일어날 수 있으며, 입력 파일이 당신의 기대를 충족하는지 확인이 있어야한다.

+0

이것은 재미있어 보이는데, 이것에 대해 살펴 보겠습니다. – Seph

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 루프를 만들면 읽은 마지막 문자가 파일의 끝이 아닌지 테스트합니다. 배열을이 코드로 채울 수 있기를 바랍니다.

+0

'fgetc'은 파일을 읽는 적절한 방법이 아닙니다. – Corbin

+0

@Corbin'getc'와'fgetc'는 C에서 이식 가능하게 파일을 읽을 수있는 가장 유연한 메커니즘입니다. – cnicutar

+0

@cnicutar 예. 그렇지만 사람들은 한 번에 한 문자 씩 실제로 읽고 싶습니다. 그것은 단지 고통스러운 것처럼 들립니다. (비록 50x50 어레이가 실제로 문자 판독이 적절할 수도 있음을 암시한다고 가정합니다.) – Corbin

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; 
} 
+0

50 * 50은 sizeof (데이터) 또는 sizeof (데이터)/sizeof (char)를 대체합니다. – BLUEPIXY

관련 문제