Reputation: 1
I want to search for a word in a file by reading only the 1st word of each line and copy the entire line whose 1st word is similar to another file. This code is reading the whole file not 1st word of each line.
#include<stdio.h>
#include<string.h>
int main()
{
int check=1;
FILE *fp,*fp1;
char ser[200],oneword[200],c;
printf("Enter the word:");
scanf("%s",ser);
fp=fopen("4HHB.pdb","r");
fp1=fopen("file2.dat","a+");
do
{
if(check!=0)
{
c=fscanf(fp,"%s",oneword);
//printf("hi %s\n",oneword);
check = strcmp(oneword,ser);
}
if(check==0)
{
//printf("Hello");
check=1;
fprintf(fp1,"%s ",oneword);
c=fgetc(fp);
while(c!=10&&c!=EOF) // The ASCII code for \n is 10
{
fputc(c,fp1);
c=fgetc(fp);
// if(c=="\n")
// break;
}
fputc(c,fp1);
}
}while(c!=EOF);
fclose(fp);
fclose(fp1);
return 0;
}
Upvotes: 0
Views: 44
Reputation: 16540
when a word matches, then the line needs to read/written.
When a word (code is currently checking all words, not just first word of each line) does not match, the rest of the line needs to be read/discarded.
strongly suggest reading each line via fgets(), then parsing the first word to make a decision if the line is to be written or discarded.
Upvotes: 1