简体   繁体   中英

Using fscanf to store words from file in an array

I am trying to write a program for some classwork that reads in a file using fscanf, and then stores each word into an array with one word in each element. Then I need to print each element of the array out on to a new line on the console.

The getty.txt file has the Gettysburg address in it with appropriate spacing, punctuation, and is multiline.

What I think is happening is that the entire text is being stored in the first element of the array, but I am not 100% sure as I am still learning to debug and write in C.

Any advice as to what I am doing wrong would be great! I currently only seem to be getting the last word and some extra characters.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void readFile();
void writeFile(char* buffer, int bufferlen);
FILE *fpread;
FILE *fpwrite;

char filebuffer[1000];
int filebufferlen = 0;


int main(int argc, char *argv[]) {
    fpwrite = fopen("csis.txt", "w");

    readFile();
    writeFile(filebuffer, filebufferlen);

    fclose(fpwrite);
    return 0;
}

void readFile() {
    char c;
    filebufferlen = 0;

    if(!(fpread = fopen("getty.txt", "r"))){
        printf("File %s could not be opened. \n", "getty.txt");
        fprintf(fpwrite,"File %s could not be opened. \n",     "getty.txt");
    exit(1);
}

    while (!feof(fpread)) {
        fscanf(fpread, "%s", filebuffer);
        filebufferlen++;
    }
}


void  writeFile(char* filebuffer, int filebufferlen) {
    for (int i = 0; i < filebufferlen; ++i){
            printf("%c\n", filebuffer[i]);
    }       
}

After fixing the compile problems:

the code does not contain any code nor data declarations to contain an array of 'words.' So naturally, nothing but the last word is actually saved so it can be printed out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM