The document describes code to open a file called "words", read the last word from that file, and write it to a new file called "lastword". It includes opening both files, reading the "words" file line by line, comparing each line to the last word, and writing the matching line to the "lastword" file.
In C- Write a few statements that open a file called --words-- and wri.docx
1. In C: Write a few statements that open a file called "words" and writes the last word in the file
to a file called "lastword".
Write a few statements that open a file called "words" and writes the last word in the file to a
file called "lastword". SUBMIT 1 char ch, file_name[25]; 2 FILE *fp; 3 char name[20] =
{"lastword"); 4 5 fpfopen("words.txt","a"); 6 7 fprintf(fp, "%s ", name); 8
9fpfopen("words.txt", "r") int i; fclose(fp); 10 printf("The contents of words.txt file are : ") )
!= EOF ) 12 while( ( ch fgetc(fp) 13 fprintf("%c",ch); 14 15 fclose(fp); 16 return
Solution
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {
char ch, file_name[25];
FILE *fp,*fn;
char name[20] = {"lastword"};
int i;
fp = fopen("f://words.txt", "a");
fprintf(fp, "%s ", name);
fclose(fp);
fopen("f://words.txt", "r");
printf("the contents of words.txt file are : ");
while ((ch = getc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
//searching a word in words.txt
fp=fopen("f://words.txt", "r");
fn=fopen("f://lastword.txt","w");
while ((fgets(file_name,25,fp)) != NULL) {
printf("%s ",file_name);
if(strcmp(name,file_name)==0)
{