#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);
}
在這裏,上面的程序,其中我喜歡讀的輸入字符串,並將其寫入文件中提供的字符串不是在文件中已經存在。
- 取輸入字符串
打開的文件中讀取模式。
如果是第一次入口文件將不存在,如果文件指針返回NULL,則創建一個文件寫入模式並寫入 輸入的字符串。
- 如果文件已經存在,然後逐行讀取文件並與輸入字符串進行比較,如果與任何行匹配則返回並關閉。
- 其他明智的在寫入模式下打開同一個文件並寫入輸入的字符串。
但它不能正常工作..
STRCMP未正確執行....具有重複的條目還它 不要進入的這個循環「duplicae發現」。
請如果有人能幫助...
你不應該使用C和C++方法一起這樣。選擇一個並堅持下去...... –
我知道,但在「c」printf和scanf中,我討厭使用它們。格式說明符你知道...只是爲了cin和cout我使用C++ lib..in原始代碼我只會使用c。 –