本文介绍了将int写入文件,不太确定缓冲区如何工作。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个int到一个文件,到目前为止我已写过:


const char buff [20];

int num = 256 //为了这个例子

sprintf(buff,"%d",num);


现在我的问题是什么做下一个。我可以使用fwrite,但我不知道
了解大小是如何工作的,我不确定它是否写出了整个

缓冲区,以及我绝对只想写出256。


我可以使用putc通过缓冲区并一次写出一个字符

,但同样的问题,我不知道是否写出了整个20

字符缓冲区或在''256'后停止。


我没有必要长时间使用这些东西,而且我完全不知道
忘记这个缓冲区的工作方式,我发现它很烦人

to必须事先分配空间。

I''m wanting to write an int to a file, and so far I have written:

const char buff[20];
int num = 256 //for the sake of the example
sprintf(buff, "%d", num);

Now my question is what to do next. I could use fwrite, but I don''t
understand how the size works, I''m not sure if it writes out the whole
buffer or not, and I definetly only want to write out "256."

I could use putc to go through the buffer and write out one character
at a time, but same issue, I don''t know if that writes out the whole 20
character buffer or stops after the ''256''.

I haven''t had to use this stuff for a long time, and I completely
forget how this buffer stuff works and I''m finding it fairly annoying
to have to allot the space beforehand.

推荐答案



为什么你不使用fprintf?


-

Ian Collins。

Why don''t you use fprintf?

--
Ian Collins.




好​​的。我还是不知道缓冲区是如何工作的。它打印出

整个缓冲区还是只是我放入的int?


假设我写道:


fprintf(outputfile,"%d",buff);

Ok. I still don''t know how the buffer works. Does it print out the
entire buffer or just the int I have placed in it?

Supposing I wrote:

fprintf(outputfile, "%d",buff);




好​​的。我还是不知道缓冲区是如何工作的。它打印出

整个缓冲区还是只是我放入的int?


假设我写道:


fprintf(outputfile,"%d",buff);

Ok. I still don''t know how the buffer works. Does it print out the
entire buffer or just the int I have placed in it?

Supposing I wrote:

fprintf(outputfile, "%d",buff);



请保留足够的背景和旅行签名。


鉴于buff是一个char [](你写了const char [],你不能写入
),你会得到不确定的行为。


如果你写了


fprintf(outputfile,"%s",buff);


你会得到相同的您可以在控制台上找到文件

你写的


printf("%s",buff);


-

Ian Collins。

Please keep enough context and trip signatures.

Given buff is a char[] (you wrote const char[], which you can''t write
into), you get undefined behaviour.

If you had written

fprintf(outputfile, "%s", buff);

you would get the same in the file as you would get on you console had
you written

printf("%s", buff);

--
Ian Collins.


这篇关于将int写入文件,不太确定缓冲区如何工作。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 14:09