텍스트 파일을 읽으려면 코드를 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
}
}
우선 :'scanf()'의 반환 값을 확인하십시오. – pmg
'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')를 사용하십시오. –
파일에 무엇이 들어 있습니까? 문자 뒤에 문자가오고 문자 뒤에 문자가 오나요? 질문이 모호합니다. – Abhi