2

I have an array being written to the file, but then I need a way to print that same information out from the file when I call the function. The first part of the code is in the main function, and the second is a second function that prints out the values that are supposed to be from the file (fp).

fp = fopen("Grue.txt", "wb");
for(i = 0; i < 5; i++)
{
    char newLine[3] = {"\n"};
    char space[2] = {" "};
    fwrite(array[i].name, strlen(array[i].name), sizeof(char), fp);
    fwrite(space, strlen(space), sizeof(char), fp);
    fwrite(array[i].height, strlen(array[i].height), sizeof(char), fp);
    fwrite(space, strlen(space), sizeof(char), fp);
    fwrite(array[i].weight, strlen(array[i].weight), sizeof(char), fp);
    fwrite(space, strlen(space), sizeof(char), fp);
    fwrite(array[i].items, strlen(array[i].items), sizeof(char), fp);
    fwrite(newLine, strlen(newLine), sizeof(char), fp);
}
fclose(fp);
fp = fopen("Grue.txt", "rb");
PrintAGrue(fp);


void PrintAGrue(FILE *a)
{
 // create End of file character onto the array being saved,
int i;
char n;
char h;
char w;
char m;

for (i=0; i<5; i++)
{
     n = fread(a[i].name,  strlen(array[i].name, sizeof(char), a);
     h = fread(array[i].height,  strlen(array[i].height, sizeof(char), a);
     w = fread(array[i].weight,  strlen(array[i].weight, sizeof(char), a);
     m = fread(array[i].items,  strlen(array[i].items, sizeof(char), a);

     printf("This grue is called %s and is %s feet tall, and weighs %s pounds, and has eaten %s things.", n, h, w, m);
}

}

1
  • 1
    So what does it do when you try this? Commented Apr 19, 2012 at 21:47

1 Answer 1

1

In PrintAGrue, it looks like you're using strlen() calls to decide how much data to read -- but how can you know the size of the string before you've read it? (Also, the parentheses don't look balanced...)

Perhaps your file format should explicitly include a length field for each string -- then you can do one fread to find the string size, and another to actually read the string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.