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

C 如何使用write()系统调用将整数写入文件,c,filesystems,buffer,system-calls,C,Filesystems,Buffer,System Calls,如何使用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 th

如何使用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
}
//写入(fd,buffer,strlen(buffer));
//write()系统调用中的缓冲区必须是char[];
//如果我想写整数,比如
对于(int i=0,i<10;i++){
写入(fd,i.?);//错误
//如何使用write()系统调用将整数写入文件
}
您可以先使用
sprintf()
函数创建字符串,然后在
write()
中使用它,例如:

char number_s[2];
sprintf(number_s,"%2d",i);
write(fd,number_s,strlen(number_s));

如果需要二进制输出:

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

如果您不确定要使用哪一种,请尝试所有三种方法,并查看结果输出文件。(如果没有“十六进制转储”程序或二进制编辑器,“二进制”输出将不容易看到。)

write(fd,&i,sizeof i)
这将按照使用
write
的方式写入二进制值。如果需要文本表示,请使用
fprintf
。遗憾的是,这将溢出
number\s
。不要忘记字符串终止符,或者
%2d
不能保证只写入2位。@WeatherVane
%2s
不会将输出限制为两个字符。@thangpx1706不清楚OP是否需要字符串。(也许,也许不是)。另外,
[2]
太小了。@Steve这只是一个例子,因为在他的问题中,
i
变量只在
0
10
的范围内,我认为2就足够了。
char number\u s[2]和普通
%d
适用于单个数字<代码>%2d
保证任何数字都会溢出。OP的例子只是一个例子;对于更大的投入,一个稳健的解决方案将毫无怨言地发挥作用。像
number\s
这样将数组大小调整到人们认为需要的大小是错误的、毫无意义的经济。