hi,
i have a struct that holds variables of different data types. i am trying to read the first character of data from a data file and store the data into the struct..
the file holds data like this:
interger 5
real 6.4
character c
so here is my code:
Code:
/* testCommand.h */
typedef struct {
char mycom[10];
int integer;
double real;
char character;
}command;
Code:
/* testCommand.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "testCommand.h"
FILE *f;
int main(int argc, char* argv[]){
int lenght, i;
char ch;
command *mycommand = (command*)malloc(sizeof(command));
f = fopen(argv[1], "r+");
if( f != NULL){
lenght = numLine(f);
printf("Number of Lines: %d\n", lenght);
for(i=0; i<(lenght); i++){
ch = fgetc(f); // get the forst character of the command
if (ch == 'i'){
fscanf(f, "%s %i", &(mycommand->mycom), &(mycommand->integer));
printf("%s %i\n", (mycommand->mycom), (mycommand->integer));
}
else if (ch == 'r'){
fscanf(f, "%s %lf", &(mycommand->mycom), &(mycommand->real));
printf("%s %i\n", (mycommand->mycom), (mycommand->real));
}
else if (ch == 'c'){
fscanf(f, "%s %c", &(mycommand->mycom), &(mycommand->character));
printf("%s %i\n", mycommand->mycom, mycommand->character);
}
else {
printf("Invalid!\n");
}
}
}
else{
perror("couldnt open");
}
return 0;
}
int numLine(FILE* fileNames){
int numLines=0;
char ch;
do{
ch = fgetc(fileNames);
if(ch == '\n')
numLines++;
} while (ch != EOF);
if(ch != '\n' && (numLines) != 0){
numLines++;
}
return numLines;
}
the program always outputs "Invalid!".
SORRY IF THE QUESTION IS WORDED BADLY.. :/