2014-10-05 60 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

相关问题