I have the functions below which reads words from a file and outputs each word using fgets and strtok where the words in the file are split by newline:
word1
word2
word3
I'm trying to mimic the functionality where the words in the file are on a single line split only by a space:
word1 word2 word3
However I seem to only be able to get the first word whilst changing the strtok char to " " and attempting to read a single line. I'm unsure what i'm missing.
#include <string.h>
#include <malloc.h>
int readLines;
char *output[255];
char *filename = "commands.txt";
char fileRead(const char *filename, char *output[255])
{
int count = 0;
char input[255];
char *line;
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file: %s\n", filename);
} else {
while(count < 255 && fgets(input, sizeof(input), file)) {
line = strtok(input, "\n");
if (line) {
output[count++] = strdup(line); /* Store replica */
}
}
fclose(file);
}
return count;
}
char *strdup(const char *str)
{
char *ret = malloc(strlen(str)+1);
if (ret) {
strcpy(ret, str);
}
return ret;
}
int main(int argc, char *argv[])
{
readLines = fileRead(filename, output);
/* read from array and pass into flag function */
for (int x = 0; x < readLines; ++x) {
printf("%s\n", output[x]);
free(output[x]);
}
return 0;
}
strtok()
. The first call will supplyinput
as the first argument tostrtok()
; the subsequent onesNULL
. – Jonathan Lefflerstderr
, notstdout
and when the error is from a system function, should useperror()
which will both output the enclosed text AND the appropriate system error message. Usually the best thing to do is callexit()
after displaying the message rather than allowing the program to continue – user3629249strdup()
is a system function exposed when the header filestring.h
is included – user3629249free()
for each of the char arrays obtained viastrdup()
– user3629249