很抱歉这个基本的问题,但是我有一个问题,只是让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,而对于写入文件的7个1b字符,它应该返回7。该文件确实存在于同一目录中;我尝试使用完整的文件路径;我已经将输出文件out
修改为777,以防这是问题所在(它不是);fread()
和fseek()
都可以正常工作,但为了简短起见,我去掉了它们。
我在这里做错了什么?任何帮助都是非常感谢的。
发布于 2016-09-28 10:35:01
fopen
没有"rw"
模式,您应该以二进制模式打开该文件,因为您需要对其执行fwrite
操作。
您需要的是"wb"
、"w+b"
或"r+b"
发布于 2016-09-28 10:35:20
fd = fopen("out","rw");
"rw“不是有效的打开模式之一。
有关详细信息,请参阅fopen(3) manual page。
您没有指定您的平台或C库。在Linux上,这个fopen()
调用失败。
https://stackoverflow.com/questions/39737092
复制相似问题