#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
static int cc =0;
static FILE* in;
static char* getkw(){
char tok[10];
int i;
cc = fgetc(in);
for(i=0; i<=(int)sizeof(tok)-1 &&isalpha(cc);++i){
tok[i]= cc;
cc = fgetc(in);
}
tok[i]=0;
return tok;
}
int main()
{
in = fopen("/dir/dir/a.txt", "r");
char *c= getkw();
printf("%s", c);
fclose(in);
return 0;
}
I've expected above code to get characters till space is reached. Also I have functions that ignore spaces from file and continue to next character which I've not shohwn here because they are (in my view) working well. The main problem here is, it doesn't get a character from file and doesn't pack them into array. The program crashes or nothing appears (if success).
tokis that you allocate it on the stack, and when the function returns, you can't rely on its contents anymore. One way is to allocatetokdynamically, as @purec hints at.cca global variable? Why isn't it local to thegetkw()function? If you didungetc(c, fp);you'd be able to reread the character after the keyword. As it is, you just throw that character away because you setccunconditionally when you callgetkw()again.