c - 随机写入输出文件的顺序?

标签 c file pointers output fseek

我编写了一个将信息写入文件的程序。文件的输出不是我期望的顺序。我有一个标题行和另外三个带有数字信息的行。标题排在第一位,然后是第三行、第一行和第二行。

请注意,该文件是在 a 模式下打开的,而不是 a+。根据各种消息来源,像 fseek() 这样的重新定位运算符应该被忽略。有一段时间,我实际上在第一行之前写了第三行之后。如果省略fseek()行,第三行实际上是写在header之前..

如果 fseek() 函数被注释掉(无论是在 a 还是 a+ 模式),输出如下所示下面的图片。

我写了一些代码来查看输出应该是怎样写的。文件中的文本肯定不是它应该的..

我试图在每次写入之前使用 fseek() 函数来查找 EOF 之前的位置,但无济于事。

我还注意到,如果我使用 fflush(writeP),那么我得到的效果与包含 fseek() 函数的效果相同。如图所示,文件仍然乱序,但第三行不再位于标题行之前。

我错过了什么?

void quickSortHelper(int* num, long startTime, long endTime, int size){
FILE *writeP = fopen(QUICKSORT_FILE, "a");
    if(writeP == NULL){
        fputs("Error opening file\n", stderr);
        exit(1);
    }

static int times = 0;
long deltaT; //change in time

if(size < STEPSIZE){//first time, write header to file
    printf("Writing header!\n");
    fprintf(writeP, " --- QUICKSORT ---\nCOUNT\tTIME\tMEDIAN\n");
}

deltaT = (clock() - startTime)/(CLOCKS_PER_SEC/1000);
//fflush(writeP);
fseek(writeP, -1, SEEK_END);

printf("Writing: %d\t%ld\t%d\n", size, deltaT, findMedian(num, size));
fprintf(writeP, "%d\t%ld\t%d\n", size, deltaT, findMedian(num, size));

if(++times == 3)
    fclose(writeP);

return;

enter image description here

注释了 fseek() 行后,输出为:

enter image description here

最佳答案

调用函数时,前 3 次不要关闭 writeP。因此,文件由多个 FILE 句柄打开,这些句柄在退出时关闭。 "a" 仅适用于相同的 FILE 句柄或数据已到达磁盘时。

关于c - 随机写入输出文件的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133689/

相关文章:

c - 如何避免在每个 "return "之前调用 free()

c - 出现链接错误 : Some Makefile Issue

c - 读取文本文件的完整内容后 fread() 失败

c - 从c中的文件中读取所有字节

php - fopen 并获取系统文件描述符

字符指针和 printf

c - C 中的指针 : why is the * needed in *address_of_x = &x when getting the address of x?

python - 如何将 ctype 指针读取/复制到 python 类中?

c++ - 传递接口(interface)函数的函数指针

C++从文本文件中读取字符串并逐字保存到链表中