strtol wont convert my string i got from reading a text file.
int getNumFiles(int archive){
off_t cur=lseek(archive,20,SEEK_SET);
if(cur==-1){
printf("lseek ERROR\n");
exit(-1);
}
bool b=true;
char headerSizeBuffer[4];
char *end;
while(b){
int numRead=read(archive,headerSizeBuffer,3);
if(numRead != 3){
printf("read ERROR\n");
exit(-1);
}
headerSizeBuffer[3]='\0';
printf("headerSizeBuffer=%s with length=%ld\n",headerSizeBuffer,strlen(headerSizeBuffer));
long headerSize=strtol(headerSizeBuffer,&end,10);//atol(headerSizeBuffer);
printf("headerSize=%ld\n",headerSize);
if (!*end)
printf("Converted successfully\n");
else
printf("Conversion error, non-convertible part: %s\n", end);
b=false;
}
return 1;
}
the console give me this when i run the compiled code
headerSizeBuffer=031l_archive with length=12
headerSize=31
Conversion error, non-convertible part: l_archive
all i want to do is convert 031 into a long or int with the value 31.
Odds are that you didn't allocate space, or enough space, for headerSizeBuffer and it is getting overwritten some time between (the start of) the call to printf and (the end of) the call to strtol.
Edit: From the comment above: "char* headerSizeBuffer"
Yup, I was right. Since you haven't allocated any space you have undefined behavior ... which means that any behavior might occur, including what you're seeing. Be sure that you allocate enough space to headerSizeBuffer, either by setting it to point to enough memory (that could be from malloc, or it could be an array, or various other less common means) or, more appropriate to your case because the size needed is known at compile time, declaring it as an array rather than a pointer:
char headerSizeBuffer[4];
Be sure to set headerSizeBuffer[3] = '\0` to terminate the string before passing it to strtol.