Created
June 18, 2013 16:26
-
-
Save semahawk/5806899 to your computer and use it in GitHub Desktop.
Reading into a struct from a file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
struct st { | |
int num; | |
char ch; | |
}; | |
int main(void) | |
{ | |
/* requires C99 */ | |
unsigned char buf[sizeof(struct st)]; | |
struct st myst = { 37, 'n' }; | |
size_t bytes; | |
FILE *f = fopen("mem.b", "wb"); | |
if (!f){ | |
perror("mem.b"); | |
return EXIT_FAILURE; | |
} | |
/* write bytes to file */ | |
if ((bytes = fwrite(&myst, sizeof(struct st), 1, f)) != 1){ | |
printf("error: fwrite wrote %lu bytes\n", bytes); | |
return EXIT_FAILURE; | |
} | |
/* close the file */ | |
fclose(f); | |
/* and reopen */ | |
if (!(f = fopen("mem.b", "rb"))){ | |
perror("mem.b"); | |
return EXIT_FAILURE; | |
} | |
/* sum debug */ | |
printf("before freading:\n"); | |
printf(" num: %d\n", myst.num); | |
printf(" ch: %c (%d 0x%x)\n", myst.ch, myst.ch, myst.ch); | |
/* zero out the struct */ | |
memset(&myst, 0, sizeof(struct st)); | |
/* sum debug */ | |
printf("after the zero-out:\n"); | |
printf(" num: %d\n", myst.num); | |
printf(" ch: %c (%d 0x%x)\n", myst.ch, myst.ch, myst.ch); | |
/* read bytes from file */ | |
if ((bytes = fread(buf, sizeof(struct st), 1, f)) != 1){ | |
printf("error: fread read %lu bytes\n", bytes); | |
return EXIT_FAILURE; | |
} | |
memcpy(&myst, buf, sizeof(struct st)); | |
/* sum debug */ | |
printf("after freading:\n"); | |
printf(" num: %d\n", myst.num); | |
printf(" ch: %c (%d 0x%x)\n", myst.ch, myst.ch, myst.ch); | |
/* close the file */ | |
fclose(f); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment