gpt4 book ai didi

c - 如何使用 write() 系统调用将整数写入文件

转载 作者:行者123 更新时间:2023-11-30 19:50:37 26 4
gpt4 key购买 nike

如何使用 write() 系统调用将整数写入文件

 //write(fd,buffer,strlen(buffer));
//The buffer in the write() system call has to be an char[];
//if i want to write integer such as

for(int i = 0, i < 10; i++){

write(fd,i.??); // error
// How can i write the integer in to the file by using the write() system call
}

最佳答案

如果你想要二进制输出:

 write(fd, &i, sizeof(i));

如果您想要文本输出,每行一个十进制数:

char tmpbuf[50];
int n = sprintf(tmpbuf, "%d\n", i);
write(fd, tmpbuf, n);

如果要文本输出,每个 int 8 个十六进制数字:

char tmpbuf[20];
int n = sprintf(tmpbuf, "%08X", i);
write(fd, tmpbuf, n);

如果您不确定自己想要哪种,请尝试所有三种方法,并查看生成的输出文件。 (如果没有“十六进制转储”程序或二进制编辑器,“二进制”输出将不容易可见。)

关于c - 如何使用 write() 系统调用将整数写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com