Skip to content
Advertisement

Rewrite at the beginning of the file

I was trying to rewriting text at beginning of file but facing the following:

The header file is test.h:

#ifndef test_h

#define test_h

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char auth_xml_val[400];

void generate_auth_xml(FILE *);

#endif

The source file is test.c :

#include"test.h"

extern int count;

char auth_xml_val[] ="UEQ5NGJXd2dkbVZ5YzJsdmJqMGlNUzR3SWlCbGJtTnZaR2x1WnowaVZWUkdMVGdpSUhOMFlXNWtZV3h2Ym1VOUlubGxjeUkvUGp4QmRYUm9JSFZwWkQw";

void generate_auth_xml(FILE *fp)
{
    char *local= (char *)malloc(sizeof(char)*(strlen(auth_xml_val)+2));
// Removing last chars
    strcpy(local,auth_xml_val);
    local[strlen(auth_xml_val)-1] = '';

    //fprintf(fp,"%06dn",1000);

    count++;
    fprintf(fp,"%sn",local);       

    count++;
    fprintf(fp,"%sn","empty");
    free(local);

    fseek(fp, 0L, SEEK_SET);
    fprintf(fp, "%dn",count);
}

The main file is main.c:

#include"test.h"

int count = 0;

int main()
{

    FILE *fp_test;

    fp_test = fopen("adhaar_auth_xml_test.txt","w+");

    if(fp_test == NULL)
    {
        printf("cannot open file.n");
        return 0;
    }

    generate_auth_xml(fp_test);

    fclose(fp_test);
    printf("Number of string count : %dn",count);
    return 0;
}

The make file is:

all : test.o main.o run

run : test.o main.o
    $(CC) -g $^ -o $@

%.o : %.c
    ${CC} -g -c $< -o $@


.PHONY : clean

clean :
    -rm -f *.o run

The out put was expected is:

2

    UEQ5NGJXd2dkbVZ5YzJsdmJqMGlNUzR3SWlCbGJtTnZaR2x1WnowaVZWUkdMVGdpSUhOMFlXNWtZV3h2Ym1VOUlubGxjeUkvUGp4QmRYUm9JSFZwWkQ

empty

But it is replacing first few characters of the first line.

2
    Q5NGJXd2dkbVZ5YzJsdmJqMGlNUzR3SWlCbGJtTnZaR2x1WnowaVZWUkdMVGdpSUhOMFlXNWtZV3h2Ym1VOUlubGxjeUkvUGp4QmRYUm9JSFZwWkQ

empty

Where I am going wrong?

Advertisement

Answer

The output is perfectly normal.

You expect you can insert characters at the beginning of the file. This is not possible. Instead your program simply overwrites the first 2 characters of the file hence the output you get.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement