简体   繁体   English

从C中的文本文件中读取字符串并确定行尾

[英]Reading strings from a text file in C and determining end of line

I am trying to read words and numbers from a space and tab delimited text file. 我试图从空格和制表符分隔的文本文件中读取单词和数字。 I need to identify lines which contain "Step" and "False". 我需要识别包含“Step”和“False”的行。 I also need to store each word or number separately so that some can be thrown out later. 我还需要分别存储每个单词或数字,以便稍后可以抛出一些单词或数字。

I am having trouble trying to write the part of the code which identifies "False" at the end of a line. 我在编写代码的一部分时遇到了麻烦,该部分代码在行尾标识为“False”。 I need the code to recognize that it has reached False and break the for loop. 我需要代码识别它已达到False并打破for循环。

Note: It is designed so that you input your own path. 注意:它的设计使您可以输入自己的路径。 This portion works. 这部分有效。 Also, I have read that fscanf is much harder to use than fgets and fputs, but the data files i am reading are very consistent in format. 另外,我已经读过fscanf比fgets和fput更难使用,但我正在阅读的数据文件在格式上非常一致。 This seems to work well for my purposes, as some entries will need to be doubles. 这似乎适合我的目的,因为有些条目需要加倍。

    int j;
    int k;
    char i[4];                       
    char File_path[40];
    char dummy;
    char stuff[7] = "False"

    printf("Input Path: ");
    scanf("%s", &File_path);
    printf("Reading:  %s\n\n",File_path);
    FILE *fp;
    fp=fopen(File_path, "r");
    for(j=0; j<7 && i != stuff; j++)
    {
        fscanf(fp,"%s",i);
        fprintf(stdout,"Read:  %s\n",i);
    }
    fclose(fp);

The file I am reading is: 我正在阅读的文件是:

True.0 kinda false False False

This returns: 返回:

Reading:  c:\\Data\\1.txt

Read:  True.0
Read:  kinda
Read:  false
Read:  False
Read:  False
Read:  False
Read:  False

I have tried changing stuff to "False" and I get the same result. 我已经尝试将内容更改为“False”,我得到了相同的结果。

You can't compare strings that way in C. You need to use strcmp() or strncmp() to do that: 您无法在C中比较字符串。您需要使用strcmp()strncmp()来执行此操作:

for (j = 0; j < 7 && strcmp(i, stuff); j++)

That loop conditional will break the first time i points to "False" . 该循环条件将在i第一次指向"False"时中断。 You also need to make i larger - you're going to overflow that buffer on the first read in your example. 你还需要使i更大 - 你将在你的例子中的第一次读取溢出缓冲区。

Editorial - you really do probably want to use fgets() and strtok() or one of its relatives to work through this stuff. 编辑 - 你真的可能想要使用fgets()strtok()或其中一个亲戚来完成这些工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM