简体   繁体   中英

opening/reading a text file in c

Hello i am running this C program on linux using gcc -Wall -std=c99 and a./out. I do not get any warnings/errors. But when i print my information read from a file i get crazy outputs. the file contains:

A13
B99
C2
D2
E44
F32
G2
H9

and the output is:

id:  A
size: 171522370
id:  C
size: 876939826
id:  4
size: 843516466

code is

typedef struct record{

    char id;
    int size;

}record; 


int main ()
{

   record reg;

    FILE *fp = NULL;


    fp = fopen("idSize.txt", "r");


    if ((fp = fopen("idSize.txt", "r")) == NULL){
      printf("error opening file");
      exit(1);
    }

    fread(&reg, sizeof(reg),1,fp);

    while (!feof(fp)){

        printf("id:  %c\n", reg.id);
    printf("size: %d\n", reg.size);


    fread(&reg, sizeof(reg),1,fp);

    }

    fclose(fp);

    return 0;

}

any help would be very appreciated! thanks a lott

Your fread is reading binary information from the file rather than the text that it actually contains. B y that, I mean it expects to find the memory image of your structure in the file, which depends on your implementation.

So, for instance (though this all varies based on your implementation's padding behaviour and type sizes), it may be expecting a single-byte char followed by three padding bytes, followed by the four-byte binary representation of an int .

You should look into using fscanf instead, which can convert for you. By way of example, the following code:

#include <stdio.h>

typedef struct record {
    char id;
    int size;
} record;

int main (void) {
    record reg;
    FILE *fp;

    if ((fp = fopen ("idSize.txt", "r")) == NULL) {
      printf ("Error opening file\n");
      return 1;
    }

    while (fscanf (fp, "%c%d\n", &(reg.id), &(reg.size)) == 2)
        printf ("id: %c, size: %d\n", reg.id, reg.size);

    fclose(fp);
    return 0;
}

produces:

id: A, size: 13
id: B, size: 99
id: C, size: 2
id: D, size: 2
id: E, size: 44
id: F, size: 32
id: G, size: 2
id: H, size: 9

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