C++/读取数据文件 我在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; path.append(“/”); append(名称); append(“/stat”); 文件*pFile; const char*c=path.c_str(); 长时间lSize; 字符*缓冲区; 结果的大小; pFile=fopen(c,“rb”); 如果(pFile==NULL){fputs(c,stderr);std::cout
我不知道您是如何获得该输出的,但我猜您正在使用printf 考虑到已将文件加载为二进制文件,当使用printf(“%s”)打印字节数组时,字符串搜索将在遇到的第一个“\0”处停止 您不能将二进制文件打印为字符串,需要逐字节写入。行C++/读取数据文件 我在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; path.append(“/”); append(名称); append(“/stat”); 文件*pFile; const char*c=path.c_str(); 长时间lSize; 字符*缓冲区; 结果的大小; pFile=fopen(c,“rb”); 如果(pFile==NULL){fputs(c,stderr);std::cout,c++,fread,C++,Fread,我不知道您是如何获得该输出的,但我猜您正在使用printf 考虑到已将文件加载为二进制文件,当使用printf(“%s”)打印字节数组时,字符串搜索将在遇到的第一个“\0”处停止 您不能将二进制文件打印为字符串,需要逐字节写入。行fwrite(cat,sizeof(char),sizeof(cat),pFile);只写入sizeof(cat)chars,它是const char指针的大小。不能使用sizeof获取动态分配的c字符串的大小。应将其替换为catStat[0]。size() 也可以使用
fwrite(cat,sizeof(char),sizeof(cat),pFile);
只写入sizeof(cat)
chars,它是const char
指针的大小。不能使用sizeof
获取动态分配的c字符串的大小。应将其替换为catStat[0]。size()
也可以使用C++构造来代替C++来编码整个程序。
你如何显示结果?它不是在代码中被忽略…如果你使用C++为什么你使用C来进行文件读取和分配?试着读一下你说文件不是文本文件,但是你是你期望一个“字符串数组”吗我不确定我是否理解。同样,显示你用来打印内容的代码。它看起来非常像一个文本文件。输出不是问题。上面的代码需要被修复。当我使用IFSITY之前它不工作,所以我切换到文件。读取的代码有任何问题。可能另一个错误是将缓冲区
复制到catStat
中的std::string
。
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++;
}