c - 如何用 C 语言读取文本文件中的字母?

标签 c fopen scanf

我使用C中的fopen代码来读取文本文件。然后我使用 fscan 代码检查该文件中是否有一个整数,该数字应为 1<= N <=5。

我想要的是当文本文件内有字母时向我显示一条警告消息,表明该文件内至少有一个字母。但如果它还没有继续执行另一个代码。

我怎样才能做到这一点? 我想将代码放在 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                   
    }
}

最佳答案

扫描 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 

关于c - 如何用 C 语言读取文本文件中的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26205003/

相关文章:

c - 红黑树 - fixTree 实现无法正常工作

c - C 中奇怪的段错误

c++ - 检查双变量是否包含整数,而不是浮点

c - 在 C 项目中声明和使用结构的正确方法?

c - 使用 fgets() 和跳行从另一个 CSV 写入 CSV

c - 随着时间的推移,文件的连续、后续加载会变得更慢

c - 读取标准输入时 scanf 的行为

php - 使用 PHP 复制图像

c - 如何添加仅允许 a-f || 之间的字母的 "(if)"A-F?

c - 在 C 中读取包含 long 数组的文件