我使用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
}
}
首先:检查'scanf()'的返回值。 – pmg 2014-10-05 17:03:56
'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
您的文件包含什么内容?它会有一些字符,然后是数字,然后是字符或数字吗?问题不明确。 – Abhi 2014-10-05 17:05:16