读入每行多个元素的文本文件

时间:2014-11-29 23:05:27

标签: c file file-io input nodes

我需要在文本文件中读取" input.in",以便我可以根据id在代码上运行排序函数。 input.in文件包含一个id和文件名,总共8行。我知道我需要逐行读取输入文件(不确定我的代码是否正确)。但主要问题是fopen函数返回的结果是它无法找到输入文件,即使它在桌面上以及源文件都保存在那里。

任何提示都将非常感谢

int main()
{
int id;
char node;
char item[9], status;

FILE *fp;

if((fp = fopen("/Users/jacobsprague/Desktop/input.txt", "r+")) == NULL)
{
    printf("No such file\n");
    exit(1);
}

while(42)
{
    int ret = fscanf(fp, "%s %c", id, &node);
    if(ret == 2)
        printf("\n%s \t %c", id, node);
    else if(errno != 0)
    {
        perror("scanf:");
        break;
    }
    else if(ret == EOF)
    {
        break;
    }
    else
    {
        printf("No match.\n");
    }
}
printf("\n");
if(feof(fp))
{
    puts("EOF");
}

return 0;
}

这是输入文件内容:

8
4 Node1111
8 Node11111111
2 Node11
7 Node1111111
1 Node1
5 Node11111
6 Node111111
3 Node111

2 个答案:

答案 0 :(得分:1)

fopen可能因为找不到文件而失败,因此您应该检查errno以查看问题所在。但是,在这种情况下,正如BLUEPIXY所提到的,问题似乎是您输入了input.txt而不是input.in

答案 1 :(得分:0)

// 1) there were lots of little oops in the ops code,
// 2) the op skipped the detail that the first line contains
//    a count of the number of following lines
// all of that is corrected in the following

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int  id;        // value read from file
    char node[30];  // string read from file
    //char item[9]; // if not commented, raises compiler warning about unused variable
    //char status;  // if not commented, raises compiler warning about unused variable
    int  ret;       // returned value from fscanf
    int  lineCount = 0; // number of lines in file after first line
    int  i;         // loop counter

    FILE *fp;
    if((fp = fopen("/Users/jacobsprague/Desktop/input.in", "r")) == NULL)
    {
        // perror also outputs the value of errno and the results of strerror()
        perror( "fopen failed for file: input.in");
        exit(1);
    }

    // implied else, fopen successful

    // get first line, which contains count of following lines
    if( 1 != (ret = fscanf(fp, " %d", &lineCount)) )
    { // fscanf failed
        perror( "fscanf");  // this also outputs the value of errno and the results of strerror()
        exit( EXIT_FAILURE );
    }

    // implied else, fscanf successful for lineCount

    for( i=0; i < lineCount; i++) // read the data lines
    {
        // note leading space in format string to consume white space (like newline)
        if( 2 != (ret = fscanf(fp, " %d %s", &id, node)) )
        { // fscanf failed
            // this also outputs the value of errno and the results of strerror()
            perror( "fscanf for id and node failed");
            break;
        }

        // implied else, fscanf successful for id and node

        printf("\n%d\t %s", id, node);
    } // end for

    printf("\n");
    if( EOF == ret )
    {
        puts("EOF");
    } // endif

    return 0;
}  // end function: main