如何在C ++中将long写入二进制文件?

时间:2016-12-10 18:50:47

标签: c++ file io binaryfiles

我有一个long数组,我想将每个元素写入二进制文件。我知道您使用(:,:,8)写入二进制文件,但write()接受两个参数:一个指向char数组(缓冲区)的指针和一个数字。由于我有一系列长片,我无法使用write()进行编写。我甚至尝试将指向long int数组的指针直接传递给第一个参数,但它产生了编译错误。

以下是我尝试做的一个例子:

write()

如何将我的long数组写入二进制文件?我已经考虑过以某种方式将longs转换为chars,但我怀疑这会有效,并且可能会有所损失在数据类型之间进行转换时的精度。另外,当我编译代码时,编译器错误留下了这个注释:" long* arr = new long [999999]; // imaginary code that fills arr with data file.write(arr,1000000); "。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

不,这正是你应该做的:

const size_t N = 999999;
long* arr = new long[N];
file.write((const char*)arr, sizeof(long)*N);

longchar作为一个简单的字节序列(即public HttpResponseMessage GetAssignmentAssessmentPdf(int id) { string pdfDocPath = HttpContext.Current.Server.MapPath("~/App_Data/LastAssignmentAssessment.pdf"); var stream = new MemoryStream(File.ReadAllBytes(pdfDocPath), 0, 0, true, true); stream.Position = 0; var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.GetBuffer()) }; result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "LastAssignmentAssessment.pdf"; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; } s),并将该序列写入文件。