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

问题描述 投票:0回答:2

如何使用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
}
c filesystems buffer system-calls
2个回答
0
投票

如果要二进制输出:

 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);

-1
投票

您可以先使用sprintf()函数创建字符串,然后在write()中使用它,例如:

char number_s[2];
sprintf(number_s,"%2d",i);
write(fd,number_s,strlen(number_s));
© www.soinside.com 2019 - 2024. All rights reserved.