fwrite()失败而不向现有文件写入任何内容

时间:2016-09-28 02:30:02

标签: c++ c

对不起这个基本问题的人,但我遇到了让fwrite()正常工作的问题?

#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main() {

    FILE* fd = NULL;
    fd = fopen("out","rw");

    if (fd == NULL) {
        printf("Open failed\n");
        return -1;
    }

    int error = 0;

    printf("Attempting write ... \n");
    char buff[] = {"hello?\n"};

    if( (error = fwrite(buff, 1, 7, fd)) != 7 ) {
        printf("fwrite() failed with code %d \n", error);
        return -1;
    }

    fclose(fd);

    return 0;
}

此代码失败 - fwrite()只返回0,而不是写入文件的七个1b字符。该文件确实存在于同一目录中;我用完整的文件路径尝试了这个;我已经将输出文件out chmod为777,以防出现问题(事实并非如此); fread()fseek()都按预期工作,但为了简洁,我将它们删除了。

我在这里做错了什么?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

fopen没有"rw"模式,您应该以二进制模式打开该文件,因为您fwrite就可以了。

您想要的是"wb""w+b""r+b"

答案 1 :(得分:0)

fd = fopen("out","rw");

&#34; RW&#34;不是有效的开放模式之一。

有关详细信息,请参阅fopen(3) manual page

您没有指定您的平台或C库。在Linux上,此fopen()调用失败。