Question
The following program takes an input as an existing text file with a name specified in a command line as the first argument, then gives
The following program takes an input as an existing text file with a name specified in a command line as the first argument, then gives an output as a new text file with a name specified in a command line as the second argument. The output file must also:
The output file should have copy of each line of the input file in the same order of lines. Each line of the output file should consist of the same words as the corresponding line in the input file but ordered backward.
In the input file words are separated by one or more spaces (' ') or by horizontal tab ('\t'). In the output file words should be separated by single space.
In the input and output files, each line ends with new line character ( ). Lines do not exceed 255 characters including new line character.
In the following code, it is made so the words in the output file are separated by a single space, and each line ends with a new line character. However, I need help making it so each line of the output file consists of the same words as the corresponding line in the input file, but ordered backwards.
Here is the code to be worked on:
#include
//open input file char str[20]={0}; strcpy(str,argv[1]); strcat(str,".txt"); FILE *ip=fopen(str,"r");
if(ip==NULL) { printf("Input file does not exist "); exit(-1); } //open or create output file FILE *op; if(argv[2]!=NULL) //checking if output file exist { strcpy(str,argv[2]); strcat(str,".txt"); op=fopen(str,"w"); } else { op=fopen("output.txt","w"); }
char buffer[255]={0}; while(fgets(buffer,sizeof(buffer),ip)) //read till end of input file { char wstr[255]={0}; char *ptr=strtok(buffer," \t"); //tokenise read string while(ptr) { strcat(wstr,ptr); strcat(wstr," "); //pad space ptr=strtok(NULL," \t"); } fprintf(op,"%s",wstr); //print to output file
}
printf("Finished "); fclose(ip); //close ip file fclose(op); //close output file return EXIT_SUCCESS; }
This is written in C
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started