我使用以下代码将结构数组插入文件,但它崩溃了:
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);
}
知道如何解决这个问题吗?
最佳答案
您多次打开文件而没有关闭它。 这将做到:
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);
}
}
如果不关闭文件,任何未写入的输出缓冲区的内容都不会写入文件。
但是您实际上应该做的是打开文件一次并执行追加操作:
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);
}
关于c - 插入数组到文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998454/