我想打开两个文件并将这些字符串保存到第三个文件中,这些文件存在于第一个文件中但不存在于第二个文件中。 因为我必须逐行读取字符串(即直到我到达下一行字符)。 但对于文件的最后一行,我没有' \ n'最后,因为有EOF .so,请帮我读取文件的所有字符串,然后存储在字符数组中..
代码: -
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f1ptr,*f2ptr,*f3ptr;
f1ptr=fopen("1stfile.txt","r");
f3ptr=fopen("3rdfile.txt","w");
char arr1[100],arr2[100];
while(fscanf(f1ptr," %[^\n]",arr1)!=EOF)
{
f2ptr=fopen("2ndfile.txt","r");
int flag=1;
while(fscanf(f2ptr," %[^\n]",arr2)!=EOF)
{
if(strcmp(arr1,arr2) ==0)
{
flag=0;//flag=0 means i will not store this string into file
}
}
fclose(f2ptr);
if(flag)
fprintf(f3ptr,"%s\n",arr1);
}
return 0;
}
我的文件如下 第一个文件
Minimum Points To Reach Destination
Maximum Index
Maximum of minimum for every window size
Find Prime numbers in a range
Largest Number formed from an Array
Find sum of different corresponding bits for all pairs
Rearrange an array with O(1) extra space
Return two prime numbers
Sorting Elements of an Array by Frequency
A Simple Fraction
QuickSort on Doubly Linked List
Reorder List
Binary Tree to DLL
Tree from Postorder and Inorder
第二档
Maximum Index
Find Prime numbers in a range
Rearrange an array with O(1) extra space
Return two prime numbers
Sorting Elements of an Array by Frequency
答案 0 :(得分:1)
以下是使用rewind()
的解决方案。
f1ptr=fopen("1stfile.txt","r");
//Check f1ptr is not NULL.
f2ptr=fopen("2ndfile.txt","r");
//Check f2ptr is not NULL.
f3ptr=fopen("3rdfile.txt","w");
//Check f3ptr is not NULL.
char arr1[100],arr2[100];
while(fgets(arr1, sizeof arr1, f1ptr) )
{
int flag=1;
rewind(f2ptr); //Moves file pointer to the top.
while(fgets(arr2,sizeof arr2, f2ptr))
{
if(strcmp(arr1,arr2) ==0)
{
flag=0;//flag=0 means i will not store this string into file
break; //Break out of the loop if 2 files have the same line.
}
}
if(flag)
fprintf(f3ptr,"%s",arr1); //No need to print newline. Its already there.
}
fclose(f1ptr);
fclose(f2ptr);
fclose(f3ptr);
如果你执行man fgets
,这里是描述的一部分:fgets()
从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。读数在EOF或换行符后停止。如果读取换行符,则将其存储到缓冲区中。终止空字节('\0'
)存储在缓冲区中的最后一个字符之后。
因此newline char被添加到字符串中但不是EOF。
答案 1 :(得分:0)
以下可行。如果你使用fgets,最后一行将添加'\ n'。
#include<stdio.h>
#include<string.h>
//using namespace std;
int main()
{
FILE *f1ptr,*f2ptr,*f3ptr;
f1ptr=fopen("1stfile.txt","r");
f3ptr=fopen("3rdfile.txt","w");
char arr1[100],arr2[100];
while (fgets(arr1, 100, f1ptr) != NULL) {
f2ptr=fopen("2ndfile.txt","r");
int flag=1;
while (fgets(arr2, 100, f2ptr)!=NULL) {
if (strcmp(arr1,arr2) ==0) {
flag=0; //flag=0 means i will not store this string into file
}
}
fclose(f2ptr);
if (flag)
fprintf(f3ptr,"%s",arr1);
}
return 0;
}