c - 插入数组到文件错误

标签 c file segmentation-fault

我使用以下代码将结构数组插入文件,但它崩溃了:

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/

相关文章:

使用 mex 编译 .C 文件包含库 - 错误 LNK2019 : unresolved external symbol - for NPTrackingTools

c - 如何将执行程序的标准输出重定向到 FCGI_stdout?

java - tTorrent 客户端错误

java - 加密和压缩文件名

c++ - 方法调用的段错误

c# - 跨语言共享常量

c - 使用 sscanf - C 将缓冲字节解析为整数

linux - 在段错误 : Is there a way, 之后检查指针是否仍然有效?

c - 使用scanf从C语言中读取txt文件

c++ - 段错误和 RAII