gpt4 book ai didi

C - 我对文件的写入丢失了

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:07 24 4
gpt4 key购买 nike

我的任务是将一些行(通常发送到标准输入)写入我选择的 .txt 文件。

使用:

#include <stdio.h>
int main(){
FILE * henry;

henry = fopen ("henry.txt", "w");

fprintf(henry, "This is some test text to be printed to a file!");
}

这正确地输出到一个文件,因为它应该。但是,当简单地将其添加到下面的代码时,它会删除我要写入的文件中的所有当前文本,但实际上并没有写入!下面是我到目前为止的代码,但它缺少其他文件。但是只看一眼,有谁知道为什么它没有输出到我指定的文件中?

//critical_example2.c
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "se207_sems.h"

int main(int argc, char argv[]){
FILE * henry;
henry = fopen ("text.txt", "w");
fprintf(henry, "This is some test text to be printed to a file!");
//Use our source file as the "key"
int id=se207_semget("critical_example2.c",1);

int pid=fork();
if(pid ){
//P1 = Process 1 is Henry.
while(1){
se207_wait(id); printf("There's a hole in the bucket, dear Liza, dear Liza,\n");
rsleep(); printf("There's a hole in the bucket, dear Liza, a hole.\n");

se207_signal(id);

se207_wait(id); printf("With what shall I fix it, dear Liza, dear Liza?\n");
rsleep(); printf("With what shall I fix it, dear Liza, with what?\n");

se207_signal(id);

se207_wait(id); printf("The straw is too long, dear Liza, dear Liza,\n");
rsleep(); printf("The straw is too long, dear Liza, too long.\n");

se207_signal(id);

se207_wait(id); printf("With what shall I cut it, dear Liza, dear Liza?\n");
rsleep(); printf("With what shall I cut it, dear Liza, with what?\n");

se207_signal(id);

}
}else{
//P2 = Process 2 is Liza
while(1){
se207_wait(id); fprintf(stderr, "Then fix it, dear Henry, dear Henry, dear Henry,\n");
rsleep(); fprintf(stderr, "Then fix it, dear Henry, dear Henry, fix it.\n");
//fprintf added to all of Liza's lines, with the location stderr being specified for output.
se207_signal(id);

se207_wait(id); fprintf(stderr, "With straw, dear Henry, dear Henry, dear Henry,\n");
rsleep(); fprintf(stderr, "With straw, dear Henry, dear Henry, with straw.\n");

se207_signal(id);

se207_wait(id); fprintf(stderr, "Then cut it, dear Henry, dear Henry, dear Henry,\n");
rsleep(); fprintf(stderr, "Then cut it, dear Henry, dear Henry, cut it.\n");

se207_signal(id);

se207_wait(id); fprintf(stderr, "With an axe, dear Henry, dear Henry, dear Henry,\n");
rsleep(); fprintf(stderr, "With an axe, dear Henry, dear Henry, an axe.\n");

se207_signal(id);
}
}
}

最佳答案

您需要调用 fflush() :

fflush(henry);

fclose() :

fclose(henry);

在你写完之后在你的 FILE* 变量上。否则,就像@AndrewHenie 建议的那样,数据可能会保留在您进程的缓冲区中,而不会在您的程序终止之前实际写入。

重要:您的代码不会检查 henry 是否为非 NULL - 如果失败,它可能是!同样,您应该检查 fflush()fclose() 的返回值。

关于C - 我对文件的写入丢失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49757358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com