我想简化一个 txt 文档,并尝试了以下代码:
#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;
}
不幸的是,尽管 infile 包含 word1、word2 和 word3 一百次,但我仍然得到 1 或 -1 作为 strcmp 的返回值。
我应该尝试什么?