[英]C++ File Operations
作為分配的一部分,我需要從一個包含int
, char
數據類型的數據的二進制文件中讀取數據。 該二進制文件分為每個記錄96字節。 我試圖將這96個字節讀取到char
緩沖區中,然后嘗試根據我所擁有的信息進行拆分。 但是,試圖讓當我得到什么int
從緩沖區值。 你能幫我嗎?
#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;
int main()
{
char buffer[100];
char *p;
char temp[10];
int val;
fstream ifs,ofs;
ifs.open("write.bin",ios::binary);
if(ifs.read(buffer,96))
{
cout << "READ" << endl;
}
p = buffer;
memcpy(temp,buffer,4);
cout << temp << endl;
val = atoi(temp);
cout << val << endl;
}
我也用strncpy
代替了memcpy
。 對於val
,輸出為0,對於temp
為空白。
atoi
將字符串(字符數組)轉換為整數。 因此,類似"42"
東西將返回整數42
。 您的問題的編寫方式聽起來像是將整數簡單地以二進制形式存儲在文本文件中。
簡單地將緩沖區指針轉換為所需的類型,再加上解除引用,就可以做到:
/* read 96 bytes into char array buffer */
uint32_t your_number = *(uint32_t*)buffer;
cout << your_number << endl;
如果要使用memcpy
,則無需復制到char數組,可以直接復制到整數地址:
uint32_t your_number;
memcpy(&your_number, buffer, 4);
cout << your_number << endl;
使用普通的C(不是C ++)將是:
uint32_t your_number;
FILE *f = fopen("write.bin", "r");
fread(&your_number, sizeof(uint32_t), 1, f); /* uint32's size is 4 bytes */
fclose(f);
printf("%d\n", your_number);
我選擇uint32_t
作為數據類型,因為它保證具有32位/ 4字節-在某些平台/編譯器上, int
可能不同。
與C樣式函數不同, read
不返回數字或讀取的字節,而是返回istream&
。 因此,要檢查結果,請在ifs.gcount()
之后調用ifs.read()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.