c - 用C打开文件,如果存在则覆盖

标签 c

我正在开发一个 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/

相关文章:

c - 无论使用什么数据大小进行分配,数组大小都会初始化为 8

android - 是否有针对 ARM(EABI)架构的特殊 C 级编程技术?

c - 指向整个数组的指针

c - 如何使用winpcap修改数据包

c - 如何在函数内创建函数并返回它们?

c++ - 是否有帮助组织#includes 的工具?

c - 变量前的加法运算符

c - 用于匹配非 ASCII 流中的模式的 Regcomp 替代方案

c - 将2个数组合并到C中的空第三个数组中

c - 如何为 RSA/AES 加密生成密码