逐行读取文件的同时读写文件

File read and write while reading the file line by line

节目:

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
    FILE *f;
    char* line;
    size_t ln=100;
    char* s;
    line=new char[100];
    s=new char[100];
    cout<<"input key"<<endl;
    cin>>s;
    f=fopen("parvin.txt","r");
    if(f==NULL)
    {
        cout<<" no file TO read so creating for writing "<<endl;
        //return 0;
        f=fopen("parvin.txt","w");
        fputs(s,f);
        fputc('\n',f);
    }
    else
    {
        while(! feof(f))
        {
            fgets(line,100,f);
            cout<<line<<endl;

            //if(!strncmp(line,s,strlen(line)-1))
            if(strcmp(line,s)== 0 )
            {
                cout<<"duplicate found"<<endl;
                fclose(f);
                return 0;
            }
        }
        fclose(f);
        f=fopen("parvin.txt","a+");
        fputs(s,f);
        fputc('\n',f);
    }
    fclose(f);
}

在上面的程序中,我喜欢读取输入字符串并将其写入文件,前提是该字符串不存在于文件中。

但是不能正常工作..

strcmp not executing properly.... with the duplicate entry also it dont go into that loop of "duplicae found" .

如果有人可以帮助...

fgets:

fgets(line,100,f);

使用f中的换行符并将其存储在line中。但是 s 不包含换行符。因此,strcmp returns 是一个非零数字,因为字符串(sf)不同。

使用

去除换行符
line[strcspn(line, "\n")] = '[=11=]';

就在 fgets 之后。 strcspn 函数,在您的例子中,returns 字符数直到 line 中的 \n。如果在 line 中找不到 \n,它 returns 字符串的长度 line(strlen(line))。


另外,请阅读 Why is while ( !feof (file) ) always wrong?。替换

while(!feof(f))

while(fgets(line,100,f)) //Same as `while(fgets(line,100,f) != NULL)`

并且不要忘记从循环主体中删除 fgets 以解决此问题。

使用 while(fgets(line,100,f)!=NULL)