views:

48

answers:

2

I am trying to read the contents of a file (which contains both 'standard' text and 'binary' data).

I then need to take that character (standard or extended ASCII) and get the corresponding Decimal (int) ASCII value.

I am having a heck of time getting it to work correctly.

Here is a snippet of the code to help show what I am currently doing...

FILE *fp = fopen(file, "r+");

char *value = NULL;

size_t charSize = sizeof(char) + 1;

value = malloc(charSize);

strcpy(value, "0");

fseek(fp, offset, SEEK_SET);

fgets(value, charSize, fp);

int c = (int)value;

free(value);

I read a thing that was saying that you needed to use an unsigned char for the extended ascii, however changing to unsigned char didn't solve the problem (and gave compile warnings)

I also tried using wchar_t with the code:

....

wchar_t *value = NULL;
value = malloc(2);

wcscpy(value, (wchar_t *)"");

fseek(fp, offset, SEEK_SET);

fgetws(value, 2, fp);

int c = (int)value;

None of these seem to work. I either get a 0 for basically everything, or some 'random' value.

For example using any of the three I get: value: % (correct) c: 76678304 (number is different each time but in this same 'range')(something tells me this isn't correct) :)

So I am obviously doing something wrong but I just can't seem to figure it out...

Any help would be very much appreciated.

+2  A: 

I think your main problem is:

int c = (int)value;

It should be:

int c = *value;

You're dereferencing value to get the character at that position. This is equivalent to value[0]. Before, you were casting a pointer to an int, which explains the large garbage values. Don't cast your problems away.

The strcpy is redundant, since fgets will write both bytes (the last being a NUL-terminator) unless it has an error or EOF. If you did want to NUL-terminate it before-hand, you would use '\0' (NUL), not '0' (ASCII digit 0). And you could simply do:

*value = '\0';
Matthew Flaschen
That seems to work GREAT for '%' using char. Do I need to use something else for extended ascii or can I still use char?
kdbdallas
You can use `char`. The extended ASCII encodings will fit in a 8-bit byte. However, it is unspecified whether `char` is signed or unsigned. So you may want to make `value` `unsigned char` to avoid negatives.
Matthew Flaschen
Actually you should instead make sure the array/string pointer type is `unsigned char *` (or cast it to such) before reading from it. BTW there is no such thing as "extended ASCII".
R..
+1 for remarking that adding explicit casts to avoid warning/errors is usually indicative that the code is wrong to begin with.
R..
A: 

Your code is far more complicated than it needs to be - you can simply do this:

FILE *fp = fopen(file, "r+");

fseek(fp, offset, SEEK_SET);

int c = fgetc(fp);
caf