Search code examples
cfseekfgetc

How to scan in a .txt file into a char in C?


I want to be able to scan in a text file into my C program so I can search and store words containing capital letters. My issue is scanning in the file.

I've tried to create a string by using fseek to determine the length of the text file, and using char[] to create the array. Then I've tried using fgetc to scan in each character into the array, but that doesn't seem to work. The for loop at the end it to verify that the scanning has worked by printing it out.

#include <stdio.h>

int main() {

    FILE *inputFile;

    inputFile = fopen("testfile.txt", "r");

    //finds the end of the file
    fseek(inputFile, 0, SEEK_END);

    //stores the size of the file
    int size = ftell(inputFile);

    char documentStore [size];

    int i = 0;

    //stores the contents of the file on documentstore
    while(feof(inputFile))
    {
        documentStore[i] = fgetc(inputFile);
        i++;
    }

    //prints out char
    for (int j = 0; j < size; j++)
    {
        printf("%c", documentStore[j]);
    }

    return 0;
}

Currently I'm getting lots of random ascii characters and I'm not sure why. I'd expect for the for loop to print out the whole txt file.


Solution

  • You need to make the following changes

    1. After int size = ftell(inputFile); add fseek(inputFile, 0, SEEK_SET); as suggested by xing

    2. Make documentStore a char pointer and allocate memory using malloc for size value

    3. while(feof(inputFile)) must be changed to while(!feof(inputFile))