c++ /读取数据文件

C++/Reading a data file

本文关键字:文件 数据 读取 c++      更新时间:2023-10-16

我在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来编写整个程序。