C Programming I was given this code to display the following as the output but i
ID: 3717195 • Letter: C
Question
C Programming
I was given this code to display the following as the output but it does not seem to work. what is wrong? or can someone guide me through the steps? thanks!
Explanation / Answer
There no such mistake in the code. just the naming convention of the file may have created the error. below code is running code. Just copy and paste and save with '.c' extension.
make sure the file you want to copy lies in the same directory where you have saved your source code.
and file must be in the format given in screenshot.
I have commented the whole code. feel free to ask if you still have any doubt
HIt thumbs up if you like the answer :)
---------------------------------------> CODE
#include<stdio.h>
int main()
{
int age;
char name[20];
FILE *infile, *outfile; // pointer to store file address
infile = fopen("myfile.txt","r"); // opening file to read the data
// file must exit in same directory where the code is saved
outfile = fopen("dupfile.txt","w");
// dupfile.txt will be created to write data.
if (infile == NULL){
//check if file myfile.txt exists
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
else
printf("Program Executed");
while(fscanf(infile,"%s%d",name,&age)!= EOF) //EOF = End Of File
//fscanf return EOF when the pointer reach to end of file
{
fprintf(outfile,"%s %d ",name,age);
}
fclose(infile); //closing the opened file
fclose(outfile);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.