프로그램은 file1
의 각 줄을보고 정확히 일치하는 줄이 file2
에 있는지 확인해야합니다. 그렇다면 출력을 line이라는 새로운 파일에 복사하십시오.C 파일 처리 : 텍스트가 파일 끝에 추가되지 않습니다.
말, 파일의 내용 (이 문장이 될 수 있지만, 간단하게하기 위해, 내가 번호를 넣었습니다.) 다음 -
(Expected) output
2
4
6
8
-
file1 file2
1 2
2 4
3 15
4 6
5 11
6 8
7
8
9
그런 다음 output
파일과 같아야은 내부 쉘은 printf가 output
을 예상대로 인쇄 할 수 있지만 fprintf가 순서를 뒤집어서 왜 이해가 안되나요? 출력 파일에 인쇄됩니다 출력은 다음
output
8
6
4
2
을 - 이것도 코드 - 당신이 각 차이에서 개방output
하고 최종이에 한 시간을 닫는
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *file1, *file2, *output;
int c;
/*Creating buffers where data will be stored for comparison*/
char buffer1[999], buffer2[999];
/*Settig the buffer characters array to 0*/
memset(buffer1, 0, sizeof(buffer1));
memset(buffer2, 0, sizeof(buffer2));
/*Open output file in "w" so that it clears the file*/
output = fopen("output", "w");
/*Open file1 and then save the line inside buffer1 (within while loop)*/
file1 = fopen("file1", "r");
/*Read each character in file until End Of Line*/
while((c = getc(file1)) != EOF)
{
int i = 0;
/*Save each new line of file1 in buffer1 for comparison*/
while(c != '\n')
{
buffer1[i++] = c;
c = getc(file1);
}
/*Open file2 and then save it's line in buffer2 (withing while loop)*/
file2 = fopen("file2", "r");
int ch;
while((ch = getc(file2)) != EOF)
{
i = 0;
while(ch != '\n')
{
buffer2[i++] = ch;
ch = getc(file2);
}
/*Compare lines of file1 against each line of file2*/
if(strcmp(buffer1,buffer2) == 0)
{
/*Save similar lines in a file named output*/
output = fopen("output", "a");
fprintf(output,"%s\n", buffer2);
printf("%s\n", buffer2);
break;
}
/*Reset the buffer*/
memset(buffer2, 0, sizeof(buffer2));
}
memset(buffer1, 0, sizeof(buffer1));
}
/*Close the output file if there were any comparison made i.e. if file was opened*/
if(output != NULL)
{
fclose(output);
}
/*Close other files*/
fclose(file1);
fclose(file2);
return 0;
}
추신 : 나는 이것에 초심자이고, 코드를 올바르게 작성했는지 확실하지 않다. 친절히 말해주세요. 고마워요. –
"w"사용하지 않음 "w +" – qrtt1