我有以下代码,
我正在尝试将两个文件的内容合并到第三个文件中,我想在第三个文件的每一行的开头添加行号。
我已将两个文件的内容合并到第三个文件中,请在下面的代码中找到,但我需要在每行的开头添加行号,请帮帮我。
# include <stdio.h>
# include <conio.h>
# include <process.h>
void main()
{
FILE *f[2],*fp,*f3;
char ch;
int i;
char file[2][20]={"E:/Structure.txt","E:/Text.txt"};
char thirdfile[20];
for(i=0;i<2;i++)
{
fp=fopen(file[i],"r");
f[i]=fp;
if(fp==NULL)
{
printf("Cannot open file");
exit(1);
}
}
printf("Enter the file to combine contents:");
scanf("%s",thirdfile);
f3=fopen(thirdfile,"w");
if(f3==NULL)
{
perror(thirdfile);
exit(1);
}
for(i=0;i<2;i++)
{
while(!feof(f[i]))
{
ch=fgetc(f[i]);
fputc(ch,f3);
}
}
fcloseall();
getche();
}
答案 0 :(得分:1)
int line_number = 0;
for(i=0;i<2;i++)
{
int start_of_line = 1;
while( (ch = fgetc(f[i])) != EOF )
{
if (start_of_line)
fprintf(f3, "%d: ", ++line_number); /* put line number in output file */
fputc(ch,f3);
start_of_line = ch == '\n';
}
}