linux下 c语言 用write open二进制写文件,Linux下用C语言fopen、fread和fwrite函数对二进制文件的操作-Go语言中文社区...
时间: 2023-07-16 10:14:03 浏览: 87
是的,Linux下可以使用C语言的write和open函数来进行二进制文件的写操作。具体可以参考以下代码示例:
```c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("test.bin", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror("open");
return -1;
}
char buffer[] = {0x11, 0x22, 0x33, 0x44};
int len = 4;
int ret = write(fd, buffer, len);
if (ret != len) {
perror("write");
close(fd);
return -1;
}
close(fd);
return 0;
}
```
另外,也可以使用C语言的fopen、fread和fwrite函数对二进制文件进行操作。示例如下:
```c
#include <stdio.h>
int main() {
FILE *fp = fopen("test.bin", "wb");
if (!fp) {
perror("fopen");
return -1;
}
char buffer[] = {0x11, 0x22, 0x33, 0x44};
int len = 4;
int ret = fwrite(buffer, 1, len, fp);
if (ret != len) {
perror("fwrite");
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
```
需要注意的是,使用fopen函数时,需要指定打开方式为"wb",表示以二进制写入方式打开文件。