I am a novice programmer and just had a question regarding the opening of .dat files in C.
I received a .dat file from a friend, and 开发者_运维技巧these were the instructions on how to open it:
The first 4 bytes contain an integer number that indicates how many subsequent bytes you can throw away. The byte after that contains the ASCII code for a single letter in the message. The next 4 bytes contain the number of junk bytes that you can throw away, and then read the next letter, etc. The last byte in the file will be the last letter in the message.
I'm really just looking for a way to view individual bytes of the file; at this point I'm fairly confused...
You can use fread()
to read bytes from the file and fseek()
to seek to a different position (e.g. to "throw away bytes").
However, to parse the first number you need to know the endianness of the file unless they are actually 4 ascii characters representing digits; in that case you could use atoi()
to get the number.
Here's some example code:
unsigned char buf[4];
FILE *fp = fopen("test.dat", "rb");
while(!feof(fp)) {
fread(buf, 4, 1, fp); // read 4 bytes
int throw_away = do_some_magic_to_get_the_number(buf);
fseek(fp, throw_away, SEEK_CUR); // skip the given number of bytes
fread(buf, 1, 1, fp); // read one byte
// your character is now in buf[0]
}
Assuming you're reading this on the same type of machine as it was written on (i.e. both are big-endian or both are little-endian), I'd probably write the code something like this:
uint32_t skip;
while (fread(&skip, sizeof(skip), 1, infile)) {
fseek(infile, skip, SEEK_CUR);
putchar(fgetc(infile));
}
If you need to deal with endianess issues, I'd probably use htonl
on the data before writing, and ntohl
on it after reading. There are, however, lots of alternatives -- XDR and ASN.1 (to name only a couple) were intended for jobs like this (though, I should add that both of those are almost certainly overkill for the task at hand).
Check out this documentation for how the file operations work.
unsigned char input buf[4];
FILE *fp = fopen("test.dat", "rb");
while(!feof(fp)) {
fread(buf, 4, 1, fp);
int skip_num = (int)buf; // should be able to cast since 4bytes = 1int and we have been told that this is an int.
for( ; skip_num >= 0; skip_num--) {}
fread(buf, 1, 1, fp); // This is the actual character do something with buf[0].
}
精彩评论