2014-10-05 2 views
-2

텍스트 파일을 읽으려면 코드를 C에 사용하십시오. 그런 다음 fscan 코드를 사용하여 1 < = N < = 5가되어야하는 해당 파일의 정수를 확인하십시오.C의 텍스트 파일에서 글자를 읽으려면 어떻게해야합니까?

내가 원하는 것은 텍스트 파일 안에 문자가 들어있어 파일에 문자가 하나 이상 있다는 경고 메시지를 표시하는 것입니다. 그러나 다른 코드로 양도하지 않은 경우.

어떻게하면됩니까? 나는 fscanf 명령 다음 코드를 삽입하고 싶은 여기 if

하기 전에 코드

FILE * fp;              //declare fp as a "fopen" command.  
fp = fopen ("xxx.txt", "r");          // opening the file "xxx.txt" 
if (fp == NULL)             // error here if there was a problem! 
{ 
    printf("Opening 'xxx.txt file failed: %s\n",strerror(errno)); // No such file or directory 
    getchar();             // wait the user press a key 
    return 0;              // returning an int of 0, exit the program 
} 
else                // if everything works..... 
{ 
    fscanf(fp,"%d",&num);           // here goes the fscanf() command 
    if(num<1 || num>5)           // set restrictions to integer 
    { 
     printf("The number must be 1<= N <= 5",strerror(errno)); // error with the integer number 
     getchar();            // wait the user press a key 
     return 0;             // returning an int of 0, exit the program 
    }    
    else               // if everything works..... 
    { 
     // some code here     
    } 
} 
+0

우선 :'scanf()'의 반환 값을 확인하십시오. – pmg

+0

'fopen'과'fscanf'는 * codes *가 아닌 * library functions *입니다. [fopen (3)] (http://man7.org/linux/man-pages/man3/fopen.3.html) 및 [fscanf (3)] (http://man7.org/)의 설명서를 읽어야합니다. linux/man-pages/man3/fscanf.3.html) 그리고 사용하고있는 다른 모든 함수의 반환 값을 테스트해야합니다. 또한, 모든 경고와 디버그 정보 ('gcc -Wall -g')로 컴파일하고 디버거 ('gdb')를 사용하십시오. –

+0

파일에 무엇이 들어 있습니까? 문자 뒤에 문자가오고 문자 뒤에 문자가 오나요? 질문이 모호합니다. – Abhi

답변

1

이 편지 인 경우 파일의 나머지 부분을 읽어보고해야 NUM에 대한 스캔 후 삽입입니다 찾은 다음 1을 반환합니다. 먼저 파일에서 위치를 가져 오므로 그 자리로 나중에 돌아가서 파일의 정수를 계속 읽을 수 있습니다. 문자가 발견되면 1을 반환합니다. 문자가 없으면 num을 스캔 한 후 파일 위치를 다시 원래 위치로 재설정합니다.

int readch = 0; 
long int filepos = 0L; 
filepos = ftell (fp); // get the file position                 
while ((readch = fgetc (fp)) != EOF) { // read each character of the file          
    if (isalpha (readch)) { // check each character to see if it is a letter          
     printf ("File contains letters\n"); 
     fclose (fp); 
     return 1; 
    } 
} 
fseek (fp, filepos, SEEK_SET); // move file position back to where it was after reading num 
+0

작품 1000000000000 %;) –

관련 문제