LANGUAGE C
The codes below reads another .c or .txt file. Then, it will read the contents of every line and store the contents into a string array.
Example: .c file that is to be read:
#include <stdio.h>
int main(){
printf("Hello World");
return ;
}
_______________(END OF THE FILE)_______________
Therefore, the code will read the contents above and store the contents in every line into an array, such that....
array[0] = "#include <stdio.h>\n"
array[1] = "\n"
array[2] ="int main(){\n "
and it goes on....
The codes below are my uncompleted code, can sir/madam show me the correct steps to do so? Any assistance is appreciated in advance.
#include<stdio.h>
int main(int argc,char **argv)
{
char array[100];
FILE *fp=fopen(argv[1],"r");
fclose(fp);
return 0;
}
NOTE: I use gcc compiler in unix environment, and the contents of the .c or .txt file is not fixed, i.e. the number of lines is not fixed.
Please comment, if you need any corrections.Please give a Thumps up if you like the answer.
Program
#include<stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
char array[100][100];
int num_rows=0;
FILE *fp=fopen(argv[1],"r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
while (!feof(fp)) {
fgets (array[num_rows], 60,
fp);
num_rows++;
}
fclose(fp);
for(int i=0;i<num_rows;i++)
printf("%s",array[i]);
return 0;
}
Output
./a.out hello.c
#include <stdio.h>
int main()
{
printf("Hello World");
return ;
}
Get Answers For Free
Most questions answered within 1 hours.