My program reads a txt file and can print all the contents one by one to the console but I have to store every variable in a different string and then print them out seperatly to the console.
Expected output is :
///////////
First word: Grep
Second word: danger
Third word: <
////////////
First word: ls
Second word: -a
Third word : -
/////////
Output of the program:
grep
danger
<
ls
-a
-
Input file content:
grep danger <
ls -a wc hw2 . c >
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char* argv[])
{
FILE * file;
file = fopen("commands.txt","r");
char *token;
const char s[2] = " ";
fseek(file,0,SEEK_END);
int length = ftell(file);
fseek(file,0,SEEK_SET);
char*string = malloc(sizeof(char) * (length+1));
char c;
int i = 0 ;
while( (c= fgetc(file)) != EOF) {
string[i]=c;
i++;
}
string[i]='\0';
token = strtok(string, s);
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return 0;
}