I want to simplify a txt document and I tried this code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
// 1. Step: Open files
FILE *infile;
FILE *outfile;
char line[256];
infile = fopen("vcard.txt", "r");
outfile = fopen("records.txt", "w+");
if(infile == NULL || outfile == NULL){
cerr << "Unable to open files" << endl;
exit(EXIT_FAILURE);
}
// 2.Step: Read from the infile and write to the outfile if the line is necessary
/* Description:
if the line is "BEGIN:VCARD" or "VERSION:2.1" or "END:VCARD" don't write it in the outfile
*/
char word1[256] = "BEGIN:VCARD";
char word2[256] = "VERSION:2.1";
char word3[256] = "END:VCARD";
while(!feof(infile)){
fgets(line, 256, infile);
if(strcmp(line,word1)!=0 && strcmp(line,word2)!=0 && strcmp(line,word3)!=0){ // If the line is not equal to these three words
fprintf(outfile, "%s", line); // write that line to the file
}
}
// 3.Step: Close Files
fclose(infile);
fclose(outfile);
getch();
return 0;
}
Unfortunately, despite the infile includes word1, word2 and word3 hundred times I still get 1 or -1 as the return value of strcmp.
What should I try?
fgetsreturns the newline character as part of the string. Since the strings you are comparing against don’t contain a newline, they will be compared as different.Since you are writing in C++, you may want to use
std::ifstreamandstd::getlineto read the file. The strings returned bygetlinewill not have the newline in them, and as an added bonus you won’t have to specify a limit on the line size.Another (unrelated) issue: Using
while (!foef(file))is wrong, and can result in the last line being read twice. Instead, you should loop untilfgetsreturns a null pointer.