Issue
I'm trying to read line from a file, when i use getline directly in the batch_mode function it works fine but when i refactor the code in a separate function it gives me a error.
int main(int argc, char *argv[]) {
if (argc > 2)
return EXIT_FAILURE;
batch_mode(argv[1]);
return EXIT_SUCCESS;
}
batch_mode function
void batch_mode(char *path) {
char *line = NULL;
ssize_t error = 0;
char *cmd = NULL;
FILE *file = fopen(path, "r");
if (file == NULL) {
printf("Coudn't read file\n");
return;
}
while (error != -1) {
read_line(line, file, cmd);
error = -1;
int thread = fork();
if (thread == 0) {
char *myargs[] = {NULL};
execv(cmd, myargs);
} else {
thread = wait(NULL);
}
}
if (file != NULL)
fclose(file);
free(line);
}
lines are read correctly in this function when printf but output null in the batch_mode function
ssize_t read_line(char *line, FILE *file, char *cmd) {
size_t len = 0;
ssize_t read = 0;
read = getline(&line, &len, file);
printf("%s\n", line);
if (read == -1) {
printf("Coudn't read line\n");
return -1;
}
char *copy = line;
cmd = strsep(©, " ");
printf("%s\n", cmd);
return 0;
}
and when trying this code it outputs that it can't read the file because it's executing more than once
void batch_mode(char *path) {
char *line = NULL;
ssize_t error = 0;
char *cmd = NULL;
FILE *file = fopen(path, "r");
if (file == NULL) {
printf("Coudn't read file\n");
return;
}
while ((error = read_line(line, file, cmd)) != -1) {
int thread = fork();
if (thread == 0) {
char *myargs[] = {NULL};
execv(cmd, myargs);
} else {
thread = wait(NULL);
}
}
if (file != NULL)
fclose(file);
free(line);
}
Solution
Code has at least these problems:
Never frees memory
read = getline(&line, &len, file);
allocates memory to line
. Code never frees it.
The calling code's free(line);
is not the updated line
of read_line()
.
Updating only local copy
cmd = strsep(©, " ");
does not update the calling code's cmd
.
Calling code is doing execv(NULL, myargs);
Instead, pass the address of the pointer. Perhaps
ssize_t read_line(char **line, FILE *file, char **cmd) {
Answered By - chux - Reinstate Monica Answer Checked By - Dawn Plyler (WPSolving Volunteer)