0

everyone. I'm just starting my journey in learning to code, starting with C. And for the past few months, I've been struggling to understand file I/O. More often than not, I don't get the output I'm looking for. I hope this simple example demonstrates my misunderstanding.

The hash table will come into play after I can get past this problem. At the moment, all I'm trying to do here is read and print out a list of names from a .txt file, and I'm doing it in preparation for a larger assignment. My code is below, along with my list (white), and the output I'm getting (black). Can someone please help me understand what's going on here? Thanks in advance.

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

bool load (char *dictionary);
unsigned int hash (char *word);

const int LENGTH = 20;
const int HASH_MAX = 20;

typedef struct _node
{
    char word[20];
    struct _node *next;
} node;

node *HASH_TABLE[20];

int main(void)
{
    FILE *dictionary = fopen("C:/Users/ahelp/OneDrive/Desktop/Dictionary.txt", "r");

    if (!dictionary)
    {
        printf("ERROR: Could not open file\n");
        return 1;
    }


    char c;
    char word[20];
    int index = 0;

    while (!feof(dictionary))
    {
        node *temp = malloc(sizeof(node));
        char get_word[20];

        fread(get_word, sizeof(get_word), 1, dictionary);

        strcpy(temp->word, get_word);
        printf("%s\n", temp->word);
    }
}

Output (black) vs Input (white)

0

The 'fread' function takes x (1 in your case) chunks of data with a stablished size(sizeof(get_word)), from a file (dictionary), and stores it in a char array variable(get_word).

The problem with your code, is that you're reading chuncks of characters from the file with 'fread', and you're treating them like they are strings.

Strings (or char arrays) should contain the '\0' character at the end, for them to work fine with functions as 'strcpy' or 'printf'.

If you want to read every word separately, you could use 'fscan' as: while(fscan(dictionary, "%s", get_word) != EOF). What this is doing is scanning the file until it finds a blank space, a tab or a new line character, and it stores it in the char variable adding the '\0' character at the end.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .