i cant understand the error

this is the code


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

printf("Please enter the file name

if((fpin=fopen(filename,"r")) == NULL)
printf("Couldnt open file %s for input

if((fpout=fopen("res.txt","w")) == NULL)
printf("Couldnt open "res.txt" for output

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


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

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 ?


  • 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
    [b]you have the
    if you get this :[/b]
    [italic]this is the last lineusername@SERVER:~$[/italic]
    isn't there.[/b]


    [red]Good luck![/red]
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!


In this Discussion