2014-10-05 62 views
-2

我使用C中的fopen代碼來讀取文本文件。然後,我使用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 2014-10-05 17:03:56

+0

'fopen'和'fscanf'不是*代碼*,而是*庫函數*。你應該閱讀[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') – 2014-10-05 17:04:01

+0

您的文件包含什麼內容?它會有一些字符,然後是數字,然後是字符或數字嗎?問題不明確。 – Abhi 2014-10-05 17:05:16

回答

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%;) – 2014-10-05 19:08:28

相關問題