Hello everyone,
I am a newbie in C and was testing a code to read text file into struct array, posted here (Best method to alloc memory for string and desalloc..)
The code compiles but I get a run time error. Please someone help me out.
Code:
//.H file
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#ifndef temp_H
#define temp_H
typedef struct temp {
char item[20];
char description[50];
char detail[10];
char manufacturer[12];
int cost;
} *ptr; // wow, structs are
void fillstruct(struct temp*,char*);
void showstruct(struct temp*);
int linein(int,char*);
#endif
//Definition file
#include "template.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
void fillstruct (struct temp *ptr,char *line){// pass in a pointer
char *tok=strtok(line," ");
strcpy(ptr->item,tok);
tok=strtok(NULL,"\"");
strcpy(ptr->description,tok);
tok=strtok(NULL," ");
strcpy(ptr->detail,tok);
tok=strtok(NULL," ");
strcpy(ptr->manufacturer,tok);
tok=strtok(NULL," ");
ptr->cost=atoi(tok);
}
void showstruct (struct temp *ptr) {
printf("\nDescription of \"%s\": %s\n"
"Made by: %s\n"
"Price: $%d\n"
"note -- %s\n",
ptr->item, ptr->description, ptr->manufacturer, ptr->cost, ptr->detail);
}
int linein (int fd, char *string) {
int i=0;
char ch;
while (ch!='\n') {
if (read(fd,&ch,1)!=1) break;
string[i]=ch;
i++;
}
return i;
}
//MAIN function
#include "template.h"
#include <stdio.h>
#include <fcntl.h>
int main (int argc, char *argv[]) {
int len,i=0,x, fd=open("example.txt",O_RDONLY);
char string[128]; // should fit
struct temp *example=(struct temp*)malloc(sizeof(*example));
while ((len=linein(fd,string))>0) {
string[len]='\0';
if (i>0) example=realloc(example,(i+1)*sizeof(*example));
fillstruct(&example[i],string);
i++;
}
close(fd);
/* now let's see if this worked */
for (x=0;x<i;x++) showstruct(&example[x]);
free(example);
return 0;
}
//text file
top "The top part" red Bob 13
side "A side part" green Cleo 2000
corner "Connects 3rd dimension" round MK 27
Note: The line in red is the source of error: My understanding from debugging report is when i = 0 ch = -52 which ch never encounters '\n'. Is that right? If so how can I fix this?
My debug report:
ch -52 char
i 0 int
temp.exe!linein(int fd, char * string) Line 35 C