c++ /读取数据文件
C++/Reading a data file
我在c++中读取数据文件(不是txt文件)时遇到了一些问题。我的代码看起来像这样
path.append("/");
path.append(name);
path.append("/stat");
FILE * pFile;
const char *c = path.c_str();
long lSize;
char * buffer;
size_t result;
pFile = fopen ( c , "rb" );
if (pFile==NULL) {fputs (c ,stderr);std::cout<<"Error"<<std::cout; exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
return buffer;
结果我得到"ài·"而不是希望的字符串数组。我认为这是某种编码错误。为了输出我的代码,我使用fwrite将其写入一个新的txt文件
catStat[0]是之前的结果
int i = 5;
FILE * pFile;
const char * cat=catStat[0].c_str();
pFile = fopen ("/root/list.txt", "a");
if(tdi!="")
{
fwrite (cat , sizeof(char), sizeof(cat), pFile);
}
else
{
fwrite(cat,sizeof(char),sizeof(cat),pFile);
while(i<10){
cat=catStat[i].c_str();
fwrite (cat , sizeof(char), sizeof(cat), pFile);
i++;
}
如果我用编辑器打开文件或在控制台中执行cat stat,我得到:
29273 (bash) S 2556 29273 2556 1025 29273 4202752 1367 3281 1 1 12 42 20 0 0 49096474 3997696 639 4294967295 134512640 135304128 3217720544 3217717576 3077456932 0 0 3686404 1266761467 3240737915 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
提前感谢,
Laurenz
我不知道你是如何得到这个输出的,但我猜你正在使用printf。
考虑到您以二进制格式加载文件,当使用printf("%s")打印字节数组时,字符串搜索将在遇到的第一个' '处停止。
你不能把二进制文件打印成字符串,你需要一个字节一个字节地写下来。
行fwrite (cat , sizeof(char), sizeof(cat), pFile);
只写sizeof(cat)
字符,这是const char
指针的大小。您不能使用sizeof
来获取动态分配的c-string的大小。您应该将其替换为catStat[0].size()
。
另外,由于这样的警告,您可能应该学习使用c++结构而不是c来编写整个程序。
- 从 bmp 文件数据创建 MFC CBitmap
- 从存储为 Windows 资源 (c++) 的 png 中获取 png 文件数据
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 获取文件数据预处理器宏
- 错误的值是使用c++从CSV文件数据写入数组
- 无法在可视C++中检索资源文件数据
- 将文本文件数据读入字符数组时提取运算符的歧义
- 如何使用curl c ++源代码发布wav文件数据,如何使用c ++使用--data-binary?
- 如何在C++中读取 UTF-8 文件数据
- 如何在结构中存储二进制文件数据
- 无法从 turbo c 程序中的文件检索文件数据
- 使用 fstream 将文件数据从当前位置保存到文件末尾
- 通过Google Protobuf发送二进制文件数据
- 在通过套接字向服务器发送文件数据时,我得到了一些垃圾值?为什么
- 如何使用dlang读取二进制文件数据
- 程序使用FSCANF读取文件数据后崩溃
- 检测二进制文件数据的端性
- C++ 从文本文件数据类型读取为结构,并将数据存储在列表的向量中
- 将 FFT 应用于 WAV 文件数据的 C++
- C++内存映射的文件数据预取