-
getline error
can someone please please tell me why this code won't work?
Code:
int main(int argc, char *argv[]){
char* tester = "makefile";
char* tester1 = "Makefile";
if (argc == 1){
fprintf(stderr, "memake: *** No targets specified and no makefile found. Stop.\n");
return 2;
}
else if (strcmp(argv[1], tester) == 0 || strcmp(argv[1], tester1) == 0){
char* file_to_read = argv[1];
FILE* fr = fopen(file_to_read, "w");
if (fr == NULL){
fprintf(stderr, "%s: trying to open file %s for read\n", strerror(errno), file_to_read);
exit(3);
}
while(1){
char* line = NULL;
size_t line_length;
int chars_read = getline(&line, &line_length, fr);
if (chars_read == -1){
if (feof(fr)){
free(line);
break;
}
perror("getline");
exit(4);
}
char* pch = strtok(line, " :");
while(pch != NULL){
printf("%s\n", pch);
pch = strtok(NULL, " :");
}
free(line);
}
fclose(fr);
}
return 0;
}
it always fails when it tries to read a file
-
trying to open file %s for read
"w" opens for writing
if you know that the filename is "makefile" why to read it from command line parameters?
-