确定输入和读取的文件是否真的为空

时间:2016-10-07 09:36:51

标签: c scanf gets isspace

我已经编写了这个void函数来检查正在读取的输入文件是否有效,但有一件事我不知道如何实现。 fseek和ftell用于确定文件是否为空,但如果文件中有空格或制表符,则它将被视为不为空(尽管它是空的)。

输入文件将包含整数和/或单词字符串。 那么有没有办法检查整个文件是否有任何整数或字符串,或者只包含空格?

我想我可能不得不使用scanf_s或gets,使用isspace ...

FILE *inp;

/* Checks to see if file can be read */
errCode = fopen_s(&inp, file_location, "r");
if (errCode != 0) {
    printf(" ERROR. File %s was not located, ensure the following directory is valid: %s\n\n ", file_name, file_location);
    *file_Error = ERROR;
    return;
}

/*Move to end of file*/
fseek(inp, 0, SEEK_END);

/*Set filesize to size at end of file*/
fileSize = ftell(inp);

/*Print error and exit if filesize is zero i.e. contains 0 bytes (no data)*/
if (fileSize == 0) {
    fclose(inp);
    printf(" ERROR. File %s contains no data. (File size = %d bytes)\n\n ", file_name, fileSize);
    *file_Error = ERROR;
    return;
}

/*Print error and exit if filesize is zero for .dats containing only spaces or \t i.e. contains 0 bytes (no data)*/

/*Reset to beginning of file for reading*/
fseek(inp, 0, SEEK_SET);

/* Checks for error reading file occured */
if (errCode != 0) {
    printf(" Error opening file %s.\n\n ", file_name);
    *file_Error = ERROR;
    return;
}

/*if no error on file*/
else
{
    printf_s(" File %s Opened.\n\n", file_name);
    *file_Error = 0;
}

0 个答案:

没有答案