AMH
AMH

Reputation: 6451

Insertion of array to file error

I use the following code to insert array of structure to file but it crash:

void SaveInFile(List * pl)
{

        int i;
        int s = ListSize(pl);

        file = fopen("myFile.txt", "w");        //3shan aktb 3la file mn gded 
        for (i = 0; i <= s; i++) {
                file = fopen("myFile.txt", "a");
                fprintf(file, "IDOfprocess%s/n", pl->entry[i].ID);
                fprintf(file, "IDOfprocess%s/n", pl->entry[i].BurstTime);
        }
        fclose(file);
}

Any idea how to solve this?

Upvotes: 0

Views: 79

Answers (2)

HelloWorld123456789
HelloWorld123456789

Reputation: 5369

You are opening the file multiple times without closing it. This will do:

void SaveInFile(List* pl)
{

int i;
int s=ListSize(pl);

file=fopen("myFile.txt","w");//3shan aktb 3la file mn gded 
fclose(file);
for( i=0;i<=s;i++){

file=fopen("myFile.txt","a");
fprintf(file,"IDOfprocess%s/n",pl->entry[i].ID);
fprintf(file,"IDOfprocess%s/n",pl->entry[i].BurstTime);

fclose(file);
}
}

If you do not close the file, the content of any unwritten output buffer is not written to the file.

But what you should actually do is open the file one time and perform the append operations:

void SaveInFile(List* pl)
{

int i;
int s=ListSize(pl);

file=fopen("myFile.txt","w");//3shan aktb 3la file mn gded 
fclose(file);

file=fopen("myFile.txt","a");
for( i=0;i<=s;i++){

fprintf(file,"IDOfprocess%s/n",pl->entry[i].ID);
fprintf(file,"IDOfprocess%s/n",pl->entry[i].BurstTime);
}
fclose(file);
}

Upvotes: 1

MOHAMED
MOHAMED

Reputation: 43548

your for loop is reaching s and you are starting from 0 (so you are treating s+1 elements and not s elements)

So it should be

for( i=0;i<s;i++){

Upvotes: 1

Related Questions