我試圖在 C 中打開一個 .dat 二進制檔案作為練習,但是當我嘗試列印出檔案的內容時,我收到的是符號而不是數字。
這是我如何讀取 .dat 檔案的代碼:
int main() {
errno_t status;
std::FILE *input_file;
status = fopen_s(&input_file, filename, "rb");
if (status == 0) {
std::string content;
std::fseek(input_file, 0, SEEK_END);
content.resize(std::ftell(input_file));
std::rewind(input_file);
std::fread(&content[0], 1, content.size(), input_file);
std::fclose(input_file);
for (int i = 0; i < 10; i ) {
std::cout << content[i];
}
}
return 0;
}
我也嘗試過使用 C fstream。
int main() {
std::ifstream input_file(filename, std::ios::in | std::ios::binary);
if (input_file) {
std::string content;
input_file.seekg(0, std::ios::end);
content.resize(input_file.tellg());
input_file.seekg(0, std::ios::beg);
input_file.read(&content[0], contents.size());
input_file.close();
for (int i = 0; i < 10; i ) {
std::cout << content[i];
}
}
return 0;
}
當我嘗試列印 的內容時content,它回傳?\|C?\|C?\(對于前 10 個元素),它對應于檔案的前 10 個位元組:(fc 5c 7c 43 fc 5c 7c 43 fc 5c根據十六進制編輯器)。
我可以通過使用輕松地在 Python 中打開檔案
data = numpy.fromfile(filename, "=f")
并回傳以下(我期望的),
array([252.36322, 252.36322, 252.36322, ..., 239.38304, 239.38304,
239.38304], dtype=float32)
I also looked into the number of bytes each element should have using Python, and it returned 4, which matches with the output of std::ftell(input_file) (the file should have 36 million points), but I tried changing 1 to 4 in the line std::fread(&content[0], 1, content.size(), input_file); and it returns an empty content. Also, as far as I know, the file doesn't contain any headers, so I think the data should begin at the very first bit.
So, how could I open and read the .dat file in C so that it returns the same value as Python?
Thank you in advance.
uj5u.com熱心網友回復:
回圈
for (int i = 0; i < 10; i ) {
std::cout << content[i];
}
通過將資料解釋為表示單個字符的字符代碼來列印資料。然而,這并不是資料所代表的。資料實際上表示單精度浮點數。因此,您應該將其解釋為:
for (int i = 0; i < 10; i ) {
float f;
std::memcpy( &f, content.data() i * sizeof f, sizeof f );
std::cout << f << '\n';
}
請注意,您必須#include <cstring>為了使用std::memcpy.
uj5u.com熱心網友回復:
您應該使用 C 的 fstream 而不是 C 函式,如下所示:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream in("batFile.bat");
if (in)
{
std::string content;
std::string line;
while (std::getline(in, line))
{
content = line '\n';
}
std::cout << content;
}
return 0;
}
bat檔案.bat
12
12
13
13
輸出
12
12
13
13
如您所見,此代碼運行良好,您可以根據需要對其進行修改:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425704.html
標籤:c
