简体   繁体   中英

Read Extended ASCII Characters from File and Convert to ASCII Decimal Value

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.

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';

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM