In: Computer Science
For c language.
I want to read a text file called input.txt for example, the file has the form.
4
hello
goodbye
hihi
goodnight
where the first number indicates the n number of words while other words are separated by newlines.
I want to store these words into a 2D array so I can further work on these.
and
there are fewer words in the word file than specified by the number in the first line of the file, then you must print an error message and return a non-zero value from main.
You must only read the first n words, you can ignore all words after n and should continue with the program as normal.
Thanks!
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE * file;
file = fopen("input.txt" , "r");
printf("Reading file...\n");
if (!file){
perror("ERROR opening file! File
not found!!!\n");
return 0;
}
char s1[100];
int count=0;
int possibleCount = 0;
fscanf(file, "%d", &possibleCount);
char words[possibleCount][100];
while (fscanf(file, "%s", s1)!=EOF)
{
strcpy(words[count],s1);
count++;
if(count==possibleCount){
break;
}
}
if(count<possibleCount){
printf("Error!!! Less amount of
words in file than expected!!!");
return 1;
}
printf("Content of the 2D array is \n");
int i;
for(i=0;i<count;i++){
printf("%s\n",words[i]);
}
return 0;
}
input.txt
4
hello
goodbye
hihi
goodnight
nice
pizza
dominoz
output