Rapid Prototyping for general microcontroller applications, Ethernet, USB and 32-bit ARM® Cortex™-M3 based designs

Char array to int issue

07 Aug 2014

Hi all,

Ive been trying to retrieve two specific characters from a file and convert them to integers. I haven't been successful with a lot of different methods. Mostly Ive been trying to use ATOI without success. Any help? When I print out the value of REC2 of my code it just prints out a 1. //

char rec[2];

FILE *fp = fopen("/sd/mydir/trailer4.txt", "r");

fseek(fp,45,SEEK_SET); rec[0]=fgetc(fp); get a character/byte from the file

fseek(fp,46,SEEK_SET); rec[1]=fgetc(fp);

int rec2= atoi(rec);

fclose(fp);

12 Aug 2014

The string should be terminated by "null character". So you may need to add one more byte in rec[] array and put zero in last element. I think next code may work ;)

sample

    char    rec[ 3 ];
    FILE    *fp      = fopen( "/sd/mydir/trailer4.txt", "r" );

    fseek( fp, 45, SEEK_SET );
    rec[ 0 ]    = fgetc( fp );
    rec[ 1 ]    = fgetc( fp );
    rec[ 2 ]    = '\0';

    int rec2= atoi( rec );

    fclose(fp);