阅读直到行尾

时间:2012-11-09 21:47:32

标签: c file

我正在尝试从C中的文件中读取作为我的项目的一部分。

我的目的是解析该文件中的单词(由空格,逗号,分号或新行字符分隔)到标记中。

为此我必须逐个字符地阅读。

do {

    do {

        tempChar = fgetc(asmCode);
        strcpy(&tempToken[i], &tempChar);

        i++;

    } while (tempChar != ' ' || tempChar != ':' || tempChar != ';' || tempChar != ',' || tempChar != '\n');//reading until the given parameters

    i = 0;

    //some other code with some other purpose

} while (tempChar != EOF);//reading until the end of the file

即使以下代码从文件中读取,它也不会停止读取,因为它不会在内部应用条件。

我在这里做错了什么?

P.S。 tempChar& tempToken被定义为char变量。另一个

2 个答案:

答案 0 :(得分:4)

我想这行代码出了问题:

while (tempChar != ' ' || tempChar != ':' || tempChar != ';' || tempChar != ',' || tempChar != '\n');

由于您使用了||,因此条件始终为true,使其成为无限循环。 试试这个,这可能有效:

while (tempChar != ' ' && tempChar != ':' && tempChar != ';' && tempChar != ',' && tempChar != '\n');

另外,我更喜欢if(feof(asmCode))而不是if (tempChar == EOF)。如果值tempChar与EOF相同,则if (tempChar == EOF)将不起作用。

答案 1 :(得分:0)

正如我在代码中看到的那样tempchar的类型是char:char tempchar

您不能使用strcpy(&tempToken[i], &tempChar);来复制char。 strcpy复制字符串到sting缓冲区。

尝试以下固定代码

do {

    do {

        tempChar = fgetc(asmCode);

        if (tempChar == EOF)
            break;
        tempToken[i]= tempChar;

        i++;

    } while (tempChar != ' ' || tempChar != ':' || tempChar != ';' || tempChar != ',' || tempChar != '\n');//reading until the given parameters
    tempToken[i]='0';
    i = 0;  // this will erase the old content of tempToken !!! what are you trying to do here ?

    //some other code with some other purpose

} while (tempChar != EOF);//reading until the end of the file
相关问题