Reputation: 9
I've been searching for a while and can't figure out my problem. What I'm trying to do is read in a .txt file full of keywords separated by commas. Then I wanted to add each individual keyword into its own index for an array to be able to access later.
I have been able to print the .txt file as is, but I can't figure out how to add the whole string of each word into the array instead of the individual characters. This array is to be used to search another .txt file for those keywords. So to clarify:
.txt file that is read in:
c, c++, java, source,
What the array looks like now
f[0]c
f[1],
f[2]c
f[3]+
f[4]+
f[5],
f[6]j
f[7]a
f[8]v
f[9]a
etc
What i'm looking to accomplish:
f[0] = c
f[1] = c++
f[2] = java
f[3] = source
etc
It was for an assignment that I couldn't finish the way I wanted. I am only curious to find out what I would need to start looking into because I think this is something a little above my current level in class. Below is the code that I have made up to print the .txt file into an array. Any information would be awesome. I haven't learned memory allocation or anything yet and this was mainly to learn about FILE I/O and search functions. Thanks again!
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#define pause system("pause")
#define cls system("cls")
#include <string.h>
main(){
FILE* pFile;
char f[50] = {""};
int i = 0;
pFile = fopen("a:\\newA.txt", "r");
if (!pFile) {
perror("Error");
}
fread(f, sizeof(char), 50, pFile);
printf("%s\n", f);
pause;
}
Upvotes: 0
Views: 165
Reputation: 40145
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getWord(FILE *fp, const char *delimiter){
char word[64];
int ch, i=0;
while(EOF!=(ch=fgetc(fp)) && strchr(delimiter, ch))
;//skip
if(ch == EOF)
return NULL;
do{
word[i++] = ch;
}while(EOF!=(ch=fgetc(fp)) && !strchr(delimiter, ch));
word[i]='\0';
return strdup(word);
}
int main(void) {
char *word, *f[25];
int i, n = 0;
FILE *pFile = fopen("a:\\newA.txt", "r");
while(word = getWord(pFile, ", \n")){
f[n++] = word;
}
fclose(pFile);
for(i=0; i<n; ++i){
puts(f[i]);
//free(f[i]);
}
return 0;
}
Upvotes: 0
Reputation: 11
char f[50] = {""};
This line means you build an empty array of 50 characters. Each f[i] will contains 1 and only 1 character. I give you this code that can print what you want but not sure if it is what you're asked to do...
main(){
FILE* pFile;
char f[50] = {""};
int i = 0;
pFile = fopen("a:\\newA.txt", "r");
if (!pFile) {
perror("Error");
}
fread(f, sizeof(char), 50, pFile);
for(int j = 0; j<50; j++) {
if(f[j] == ',') {
printf("\n");
} else {
printf("%c", f[j]);
}
}
pause;
}
This will print your words, delimited by ','... but your array will remain the same !
Upvotes: 1