Write a well-commented C program that accepts the name of a file and a \"field-n
ID: 3713134 • Letter: W
Question
Write a well-commented C program that accepts the name of a file and a "field-number" from the user, and then reads that file and for each line in that file prints on the terminal word at position "field-number" and also writes the word into an output file. For example, if the input file as the following lines:
C is a programming language.
lex produces a lexical analyser
cc is a compiler
and if the field-number specified is 4, then the output of the program is:
programming
lexical
(NULL)
compiler
Explanation / Answer
The required code for completing the task is given below. Read the specified input file line by line, tokenized the words and found the word at target field number, displayed it and saved to a file. Comments are included in every statements.Thanks.
//code.c
#include<stdio.h>
#include <string.h>
int main(){
char filename[50];//for storing input file name
char outputfilename[]="result.txt"; //output file name
int required_field; //for storing required field number
FILE *fp,*ofp;//defining file pointers for input and output files
//reading input file
printf("Enter file name: ");
scanf("%s",&filename);
fp=fopen(filename,"r");//reading input file in read mode
//making sure input file exist and is readable
if(!fp){
printf("File not found! ");
return 0;
}
//getting field number
printf("Enter field number: ");
scanf("%d",&required_field);
//opening output file for writing
ofp=fopen(outputfilename,"w");
char line[250];//buffer for storing each line of text
char *word_token; //used for tokenizing each line
int field_number=0; //used for iterating through each word (field)
//looping through each line
while (fgets(line, sizeof(line), fp)) {
//tokenizing the line (splitting it by delimeters - white spaces
// or next line character )
word_token=strtok (line," ");
field_number=1;
//looping through each tokens until target field
//or until word token becomes null
while(field_number!=required_field && word_token!=NULL){
word_token = strtok (NULL, " ");//getting next token
field_number++;
}
if(word_token==NULL){
//null value, displaying and saving to file
printf("(NULL) ");
fprintf(ofp,"(NULL) ");
}else{
//field value at given position, displaying and saving to file
printf ("%s ",word_token);
fprintf(ofp,"%s ",word_token);
}
}
fclose(fp);
fclose(ofp);
}
//output
Enter file name: students.txt
Enter field number: 2
Alice
Bob
Dave
Eric
Chris
Zaid
Emily
//students.txt (used input file)
123 Alice Al 3.4
587 Bob bobby 3.8
228 Dave D 3.1
321 Eric Erix 2.5
555 Chris christy 3.9
710 Zaid Z 3.2
124 Emily Clay 3.7
//results.txt(after running the program)
Alice
Bob
Dave
Eric
Chris
Zaid
Emily
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.