How to insert all the words from text file into 2D array with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define LEN 20
#define TOTALWORDS 300
 
int addAllWordsToArray(char file[], char words[][LEN]) {
    FILE *fp = fopen(file, "r");  
     
    if (fp == NULL) {
        printf("Error open file\n");
        exit(EXIT_FAILURE);
    }
     
    int i = 0;
    char word[20] = "";
    while (fscanf(fp, "%s", word) != EOF) {
        strcpy(words[i], word);
		i++;
	}
 
    fclose(fp);
 
    return i; // totalwords
}
     
void readFile(char file[]) {
    FILE *fp = fopen(file, "r");
            
    char ch;
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);
     
    fclose(fp);
}
       
int main()
{
    char file[100] = "d:\\data.txt";
    char words[TOTALWORDS][LEN] = {"", ""};
     
    readFile(file);
    puts("\n");
     
    int totalwords = addAllWordsToArray(file, words);
     
    for (int i = 0; i <  totalwords; i++) {
       printf("%s\n", words[i]);
    }    
         
    return 0;
}
        
          
          
          
/*
run:
          
c cpp csharp
java python go
javascript php nodjs

c
cpp
csharp
java
python
go
javascript
php
nodjs
       
*/

 



answered Jul 9, 2020 by avibootz

Related questions

2 answers 138 views
2 answers 181 views
1 answer 175 views
1 answer 171 views
1 answer 168 views
1 answer 152 views
...