我正在开发一个 C 程序。我无法打开文件并覆盖它(如果存在)。我认为代码是正确的,它是附加的。
int in, out, append ,pid;
if (sc->infile)
{
in = 1;
printf("infile");
}
if (sc->outfile){
out = 1;
printf("outfile");
}
if (sc->append)
append = 1;
if ((pid = fork()) < 0)
perror("some erro");
else if (pid == 0)
{
/* Be childish */
if (in)
{
int fd0 = open(sc->infile, O_RDONLY);
dup2(fd0, STDIN_FILENO);
close(fd0);
}
if (out)
{
printf("outfile detece");
int fd1;
if (append)
fd1 = open(sc->outfile, O_WRONLY | O_CREAT | O_APPEND, 0666);
else
fd1 = open(sc->outfile, O_WRONLY | O_CREAT , 0666);;
dup2(fd1, STDOUT_FILENO);
close(fd1);
}
execvp(sc->argv[sc->cmdStart[0]], &(sc->argv[sc->cmdStart[0]]));
fprintf(stderr, "Failed to exec\n" );
exit(1);
}
else
{
/* Be parental */
wait(0);
}
有人可以帮忙解决这个问题吗?我已经尝试了很多方法来解决这个问题。
最佳答案
声明
outputFd = open(sc->outfile, O_WRONLY | O_CREAT, 0666);
看起来正确,只需确保 sc->outfile
正确即可。您是否打印了 open()
的返回值或 perror("open()")
所说的内容。
来自open
的手册页
Return Value
open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
同时打印errno
。例如
int outputFd;
outputFd = open(sc->outfile, O_WRONLY | O_CREAT , 0666);
if(outputFd == -1) {
/* Error handling */
}
它是附加的?不,您提到的代码快照不可能。如果您可以使用O_APPEND
。
关于c - 用C打开文件,如果存在则覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50770261/