I had some issues with reading a data file(not a txt file) in c++. My code looks like this
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;
As a result i get "ài· " instead of the wished string array. I think it is some kind of an encoding error. To output my code I use fwrite to write it in a new txt file
catStat[0] is the previous result
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++;
}
If i open the file with an editor or do cat stat in the console i get:
29273 (bash) S 2556 29273 2556 1025 29273 4202752 1367 3281 1 1 12 4 2 1 20 0 1 0 49096474 3997696 639 4294967295 134512640 135304128 3217720544 3217717576 3077456932 0 0 3686404 1266761467 3240737915 0 0 17 0 0 0 0 0 0
Thanks in advance,
Laurenz
I don't know how you get that output, but I'm guessing you are using printf.
Considering that you loaded the file as binary, when printing the byte array using printf("%s") the string search will stop at the first '\\0' encountered.
You cannot print a binary as a string, you need to write it down byte by byte.
The line fwrite (cat , sizeof(char), sizeof(cat), pFile);
only writes sizeof(cat)
chars, which is the size of the const char
pointer. You can't use sizeof
to get the size of a dynamically allocated c-string. You should replace that with catStat[0].size()
.
Also, you should probably learn to code the entire program with c++ constructs instead of c because of caveats like this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.