Given: code is written in ANSI C; I know the exact nature of the strings to be read (the file will be written by only this program); file can be either in text or binary (preferably binary as the files may be read repeatedly); the amount and size of strings in the array won't be known until run time (in the example I have it in the code explicitly, but in practice the arguments will be taken in though argv)
Basically, I'm dumping the input arguments into a file and rereading them back out.
Expand|Select|Wrap|Line Numbers
- #include <stdio.h>
- #include <string.h>
- int binsize(char name[], int size[])
- {
- FILE *fp;
- if ((fp = fopen(name, "rb")) == 0) {
- fprintf(stderr, "Unable to open %s", name);
- return 1;
- }
- fread(size, sizeof(size[0]), 1, fp);
- fclose(fp);
- return 0;
- }
- int readbin(char name[], char *strings[])
- {
- FILE *fp;
- int i;
- int size[1];
- if ((fp = fopen(name, "rb")) == 0) {
- fprintf(stderr, "Unable to read %s", name);
- return 1;
- }
- fread(size, sizeof(size[0]), 1, fp);
- int stringlengths[size[0]];
- fread(stringlengths, sizeof(stringlengths[0]), size[0], fp);
- for (i = 0; i < size[0]; i++) {
- fread(&strings[i], sizeof(char), stringlengths[i], fp);
- }
- fclose(fp);
- return 0;
- }
- int writebin(char name[], char *strings[], int numberofstrings)
- {
- FILE *fp;
- int i;
- if ((fp = fopen(name, "wb")) == 0) {
- fprintf(stderr, "Unable to write to %s", name);
- return 1;
- }
- fwrite(&numberofstrings, sizeof(numberofstrings), 1, fp);
- int stringlengths[numberofstrings];
- for (i = 0; i < numberofstrings; i++)
- stringlengths[i] = strlen(strings[i]) + 1; /* + 1 because strlen does not include '\0' */
- fwrite(stringlengths, sizeof(stringlengths[0]), numberofstrings, fp);
- for (i = 0; i < numberofstrings; i++)
- fwrite(strings[i], sizeof(char), stringlengths[i], fp);
- fclose(fp);
- return 0;
- }
- int main(int argc, char *argv[])
- {
- char *strings[] = {"Howdy", "ADAS", "hjkl"};
- writebin("test.bin", strings, 3);
- int size[1];
- binsize("test.bin", size);
- char *readstrings[size[0]];
- readbin("test.bin", readstrings);
- printf("%s\n", &readstrings[0]);
- system("PAUSE");
- return(0);
- }
For example, this works fine.
Expand|Select|Wrap|Line Numbers
- int main()
- {
- char *strings[] = {"Howdy", "ADAS", "hjkl"};
- printf("%s\n", strings[0]);
- system("PAUSE");
- return(0);
- }