i cant understand the error

this is the code

#include
#include


int main(void)
{
FILE *fpin, *fpout;
int ch,position;
unsigned line=1;
char filename[100];

printf("Please enter the file name
");
scanf("%s",&filename);

if((fpin=fopen(filename,"r")) == NULL)
{
printf("Couldnt open file %s for input
",filename);
exit(1);
}

if((fpout=fopen("res.txt","w")) == NULL)
{
printf("Couldnt open "res.txt" for output
");
exit(1);
}

fprintf(fpout,"%d ",line);
while ((ch=getc(fpin)) != EOF)
if( ch == '
')
{
putc(ch,fpout);
fprintf(fpout,"%d ",++line);
}
else
putc(ch,fpout);

fclose(fpin);
fclose(fpout);

return 0;
}


$ more input.txt
this is the first line
this is the second line
this is the third line

$ more res.txt
1 this is the first line
2 this is the second line
3 this is the third line
4


It seems that something happens and it cant read the EOF char.
OR even it reads it does something wrong.
I cant understand why.

I ve double-checked the input file if it has another new line char but it doesnt have one. I ve checked it with vi as well and there is no other char after the last char.

Could you please help me on this strange issue ?




Comments

  • Hi,

    Are you completely sure the last 0x0A char isn't there ?

    Editors like vi, vim, gedit, usually appends a new line
    even when you don't see it (I meant .. you can't see a new line, but you can't get into the next one also, but ... it's there!). Try to use [italic]:%!xxd[/italic] inside vim on your input.txt (to filter with xxd and get the hexadecimal view, you can't edit from there, it's only a view). (A note, Microsoft Notepad doesn't add anything.)

    Or use [italic]biew[/italic] (F2 - Hex) or midnight commander [italic]mc[/italic] (F3View - F4Hex) to observe that effectively the 0x0A char is there.

    Even easier ... try :

    [b]cat input.txt
    if you get this :[/b]
    [italic]this is the last line
    username@SERVER:~$[/italic]
    [b]you have the
    but
    if you get this :[/b]
    [italic]this is the last lineusername@SERVER:~$[/italic]
    [b]the
    isn't there.[/b]

    Regards,

    [red]Good luck![/red]
    [blue]Hackman[/blue]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion