我不知道为什么我总是在将整数写入文件时遇到麻烦。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main (int argc, char* argv[]) {
int fd, w;
int num=80;
fd=open ("file3.txt", O_CREAT|O_WRONLY, 0777);
if (fd>0) {
w=write (fd, &num, sizeof (int));
if (w==-1) {
printf ("Writing Error \n");
return EXIT_FAILURE;
}
}
close (fd);
return EXIT_SUCCESS;
}
有谁知道它会是什么吗?
非常感谢...
最佳答案
您正在将二进制值写入文件,而不是 ascii。如果你想在文件中使用 ascii,你需要先 sprintf
到 char
缓冲区,然后 write
char 缓冲区。或者使用 fopen
而不是 open
打开文件并使用 fprintf
。
附注你想要 close(fd)
在你的 if (fd > 0) {
block 中。此外,从技术上讲,open
的唯一错误返回是 -1
。所有其他值(正、零、负)都是成功的。
关于C Linux - 不写整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12631460/