【问题标题】:Insertion of array to file error将数组插入文件错误
【发布时间】:2014-01-08 14:31:51
【问题描述】:

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

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);
}

知道如何解决这个问题吗?

【问题讨论】:

  • 如果ListSize 为具有 N 个元素的列表返回大小 N,则:for( i=0;i&lt;=s;i++)for( i=0;i&lt;s;i++),否则您将得到 分段错误。跨度>
  • 您在循环内调用fopen()(即,对于每个条目)。删除第二个fopen()。另外,IDBurstTime 是什么数据类型?您正在使用 %s 这意味着以空字符结尾的字符串,所以希望它们确实是字符串。
  • 1) fopen 首先在“a”模式下打开文件,除非你想“截断”它,但无论如何你不能打开它 s+1 次,因此 2) 从内部删除 fopen lloop
  • 哎哟...我敢打赌这会泄漏内存...调用fopens 次没有fclose...不要那样做哦,检查@ 987654332@ 也由fopen 返回。如果是NULL,就出问题了

标签: c file segmentation-fault


【解决方案1】:

您多次打开文件而没有关闭它。 这样就可以了:

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);
}

【讨论】:

  • 你仍然需要关闭第一个 fopen 或者你有资源泄漏......可能只是评论它。
  • 如何将换行写成 \n 打印相同的字符而不是换行
【解决方案2】:

您的for 循环到达s 并且您从0 开始(因此您正在处理s+1 元素而不是s 元素)

应该是这样的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多