我使用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/