xem2189
September 24th, 2009, 07:33 PM
Okay so this is my first post and I hope someone can help. I've been writing this program for a class and it is essentially done except for this one part which I've attached. Basically I want to open a file, in this case it is a list of words in the file linux.words, and then allocate memory so I can put the words into an array. Well I figured first that I need to know how many words were in the file and since I don't know any real shortcut on how to do that I wrote the code below to count how many times it scans in a word and use that number to allocate memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
// Initialize variables
FILE *dictionaryFile; // Dictionary
char **dictionary; // Array to hold dictionary
char dictionaryword; // Word in the dictionary
int num_word = 0;
// Check if correct number of command line arguments
if(argc != 2)
{
printf("\nError, insufficient command line arguments!");
printf(" Exiting.\n\n");
return 0;
}
// Open file
dictionaryFile = fopen(argv[1], "r");
// Verify file opened successfully
if(dictionaryFile == NULL)
{
printf("\nError, dictionary file %s could not be opened\n\n", argv[1]);
return 0;
}
fscanf(dictionaryFile, "%s", &dictionaryword);
// Calculate the number of words in the dictionary
while(!feof(dictionaryFile))
{
fscanf(dictionaryFile, "%s", &dictionaryword);
printf("%d\n", num_words);
num_words ++;
}
// Close the dictionary file
fclose(dictionaryFile);
return 0;
}
Problem: I keep getting a seg fault at the end of my while(!feof....) and I have absolutely no idea why that is happening. If someone could explain this to me that would be great.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
// Initialize variables
FILE *dictionaryFile; // Dictionary
char **dictionary; // Array to hold dictionary
char dictionaryword; // Word in the dictionary
int num_word = 0;
// Check if correct number of command line arguments
if(argc != 2)
{
printf("\nError, insufficient command line arguments!");
printf(" Exiting.\n\n");
return 0;
}
// Open file
dictionaryFile = fopen(argv[1], "r");
// Verify file opened successfully
if(dictionaryFile == NULL)
{
printf("\nError, dictionary file %s could not be opened\n\n", argv[1]);
return 0;
}
fscanf(dictionaryFile, "%s", &dictionaryword);
// Calculate the number of words in the dictionary
while(!feof(dictionaryFile))
{
fscanf(dictionaryFile, "%s", &dictionaryword);
printf("%d\n", num_words);
num_words ++;
}
// Close the dictionary file
fclose(dictionaryFile);
return 0;
}
Problem: I keep getting a seg fault at the end of my while(!feof....) and I have absolutely no idea why that is happening. If someone could explain this to me that would be great.