Deleting last line from file in C - creates empty line
<p>I want to delete a given line in a text file so I use a temporary file writing all lines except the one we want to delete.</p>

<p>Everything is okay except for the last line of the file: when I want to delete the last line the result is an empty line in place of the deleted line but it should have nothing and not an empty line</p>

<pre><code>char line[255];
unsigned int countline=0;
unsigned int linetodelete;//fixed by the user

FILE *file=fopen(filename,"r");
FILE *filetemp=fopen("__tempfile__","w");

while(fgets(line,255,file)!=NULL){
    if(countline!=linetodelete)
        fputs(line,filetemp);
    countline++;
}

fclose(file);
fclose(filetemp);

file=fopen(filename,"w");
filetemp=fopen("__tempfile__","r");

while(fgets(line,255,filetemp)!=NULL)
    fputs(line,file);

fclose(file);
fclose(filetemp);
remove("__tempfile__");
</code></pre>

<p>file example: (I add line number to illustrate what we can see in the file)</p>

<pre><code>000 line0
001 line1
002 line2
</code></pre>

<p>result when asking to delete line 1 (001):</p>

<pre><code>000 line0
001 line2
</code></pre>

<p>result when asking to delete line 2 (002):</p>

<pre><code>000 line0
001 line1
002
</code></pre>

<p>see the blank line ? Why is this ? How to deal with it ? Thanks</p>

<p>EDIT: precisions</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

void deleteline(const char *filename,unsigned int linetodelete){
    FILE *file=fopen(filename,"r");
    FILE *filetemp=fopen("__tempfile__","w");

    char line[255];
    unsigned int countline=0;

    while(fgets(line,255,file)!=NULL){
        if(countline!=linetodelete)
            fputs(line,filetemp);
        countline++;
    }
    fclose(file);
    fclose(filetemp);
    rename("__tempfile__",filename);
}
void print(const char *filename){
    FILE *file=fopen(filename,"r");

    char line[255];
    unsigned int countline=0;

    while(fgets(line,255,file)!=NULL){
        printf("%03d ", countline);
        printf("%s",line);
        countline++;
    }
    printf("\r\n");
    fclose(file);
}
int main(){
    printf("before\n");
    print("test.txt");
    deleteline("test.txt",2);
    printf("after\n");
    print("test.txt");
}
</code></pre>

<p>before:</p>

<pre><code>cat -n test.txt 
1   line0 
2   line1 
3   line2
</code></pre>

<p>after: </p>

<pre><code>cat -n test.txt
1   line0 
2   line1 
</code></pre>

<p>and here is what I get in my file editor:</p>

<p><a href="https://imgur.com/8Wbiwk2" rel="nofollow noreferrer">http://imgur.com/8Wbiwk2</a></p>

<p>in term:</p>

<p><a href="https://imgur.com/WGNSmgf" rel="nofollow noreferrer">http://imgur.com/WGNSmgf</a></p>