gpt4 book ai didi

c - 从文件中读取字符串,直到我们得到 '\n' 字符或 c/c++ 中的 EOF

转载 作者:行者123 更新时间:2023-11-30 14:57:30 26 4
gpt4 key购买 nike

我想打开两个文件并将这些字符串保存到第三个文件中,该文件存在于第一个文件中但不存在于第二个文件中。为此,我必须逐行读取字符串(即直到到达下一行字符)。但是对于文件的最后一行,我最后没有 '\n' 因为有 EOF 。所以,请帮助我读取文件的所有字符串并将其存储在字符数组中。

代码:-

#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

最佳答案

这是使用 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()从流中读取最多一个小于 size 的字符并将它们存储到s 指向的缓冲区。读取在 EOF 或换行符后停止。如果读取换行符,则将其存储到缓冲区中。终止空字节 ('\0') 存储在缓冲区中最后一个字符之后。

因此换行符被添加到字符串中,但不是 EOF。

关于c - 从文件中读取字符串,直到我们得到 '\n' 字符或 c/c++ 中的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43886707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com