I think you should hand this in and tell me what grade i got
Anyway, your for loop will give you problems because when i==1, unless you have zeroed out imat (have you allocated it memory at all?) you won't know what imat[2] will be (shouldn't these be 0 and 1, not 1 and 2? It's the same problem anyway) but whatever it is, it won't be something read from the file. Actually your for loop is quite messed up, I think; "i" will not iterate as part of the inner while loop, so it will always be 1 while you are reading from the file, so you will always overwrite the previous character and be unable to find ".i" If you want to rewrite it a bit and ask again I might be able to help you further.
Also make your fscanf line more specific and just grab the int. I used sscanf because of my method, but it works the same:
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char *buffer=NULL;
int nextline (FILE *stream) {
int chr, i=0;
if ((buffer=malloc(2))==NULL) return -1;
while ((chr=fgetc(stream))!=EOF) {
if (chr=='\n') {
buffer[i]='\0';
return i+1;
}
buffer[i]=chr;
i++;
if ((buffer=realloc(buffer,i+2))==NULL) return -2;
}
buffer[i]='\0';
return 0;
}
int main() {
char *ptr, lookfor[2]=".i";
int llen, found;
FILE *fstRO=fopen("/root/test/text.txt","ro");
if (fstRO==NULL) {
puts("Couldn't open file...");
return -1;
}
while ((llen=nextline(fstRO))!=0) {
if (llen<0) {
printf("in nextline(): Memory Allocation Failed! (%d)\n",llen);
return -2;
}
while (((ptr=strchr(buffer,lookfor[0]))!=NULL) && ptr[1]==lookfor[1]) {
if ((sscanf(ptr,".i%d",&found))==1) printf("Found a %d...\n",found);
ptr[0]=' ';
}
free(buffer);
}
puts("Done.");
fclose(fstRO);
return 0;
}
The input test file I used looked like this:
Code:
Jamie lynn:20
Eric D. Mcdaniel:40
.i10001 12
Joe:20
.i 2 then .i 624
more .i 7
1234567890
etc
.i44 20081117_ABC1E_1_Prod
20081118_DEF5G_3_Prod
20081117_ABC1E_12_Prod
and my output was:
Found a 10001...
Found a 2...
Found a 624...
Found a 7...
Found a 44...
Done.