I just need to know how to pass and declare a FILE* array into a function
void openInputFiles(char* name, FILE* input[]){
char filename[10];
if (strcmp("average", name) == 0){
int i;
int k =1;
for (i=1;i<=10;i++){
if (i<10){
sprintf(filename,"%s_00%d",name,k);
}
if (i == 10){
sprintf(filename,"%s_0%d",name,k);
}
input[i-1] = fopen(filename,"r");
k++;
}
}
if (strcmp("median", name) == 0){
int i,k;
k=1;
for (i=1;i<10;i++){
sprintf(filename,"%s_00%d",name,k);
input[i-1] = fopen(filename,"r");
k++;
}
}
}
That's the code for the function and this is where I am trying to call it
int main(int argc, char* argv[]){
FILE* input[10];
openInputFiles(argv[1],input);
}
I don't get any warnings when I compile this but when I try to gdb it to test what's wrong it's seeming that the FILE* isn't allocating a memory address to input[0] because it says its at address 0x0. What am I doing wrong?
char filename[10];
...
sprintf(filename,"%s_00%d",name,k);
As user3121023 correctly noted, there isn't enough space to fit "average_001" into the 9 characters (plus terminating NUL) that you've allocated for the filename. You need to make it char filename[12]; or bigger. As a result, your program exhibits undefined behavior, which means anything could happen.
You should also ~never use sprintf -- use snprintf instead, and always check for errors, like this:
if (snprintf(filename, sizeof(filename), "%s_00%d", name, k) >= sizeof(filename)) {
abort(); // filename is too short.
You can also simplify your loops (there is absolutely no need to handle i == 1 through 9 differently from i == 10:
for (i = 0; i < 10; i++) {
int n = snprintf(filename, sizeof(filename), "%s_%03d", name, i + 1);
if (n == -1 || n >= sizeof(filename) {
// handle format error or "filename" too short here.
}
input[i] = fopen(filename, "r");
if (input[i] == NULL) {
// handle fopen failure here.
}
}
Related
I know the segfault is located within the argv[y] but I don't understand why! I'm very new to UNIX and rusty on my C. Any help would be awesome. (printfs were a messy way to find where the segfault was!)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *);
int see_more();
int main(int argc, char *argv[])
{
FILE *fp;
int i;
int loc;
int x;
int y;
char buffer[LINELEN];
FILE *t;
FILE *out;
FILE *read;
for(i=1; i<argc; i++){
if(strcmp(argv[i], "-o") == 0)
loc = i;
else if((t = fopen(argv[i], "r")) != NULL){
x = i;
fclose(t);
}
else{
y = i;
}
}
if(loc != -1){
FILE *read;
printf("1");
read = fopen(argv[x], "r");
printf("2");
out = fopen(argv[y], "w");
printf("3");
while(fgets(buffer, LINELEN, read))
printf("4");
fputs(buffer, out);
printf("5");
fclose(read);
fclose(out);
}
}
As yano mentioned, some variables can be left uninitialized, which will cause the segmentation fault. Enable compiler warnings (-Wall for most compilers) and fix all warnings it gives.
Using getopt() as Fiddling Bits mentioned would be great.
Another issue with your code is the check for whether an argument is the input file or the output file is bad. If the input file doesn't exist, or there is already a file with the same name as the output file, the check gives the wrong answer. Here is a better approach to parsing arguments, if you couldn't use getopt():
const char *input_filename = NULL;
const char *output_filename = NULL;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-o") == 0) {
if (output_filename != NULL || i + 1 >= argc) {
fprintf(stderr, "Error parsing arguments: double use of -o or missing filename\n");
return 1;
}
output_filename = argv[++i];
} else {
if (input_filename != NULL) {
fprintf(stderr, "Error parsing arguments: more than one input specified\n");
return 1;
}
input_filename = argv[i];
}
}
if (input_filename == NULL || output_filename == NULL) {
fprintf(stderr, "Error parsing arguments: missing input and/or output filename\n");
return 1;
}
FILE *read = fopen(input_filename, "r");
// add error checking here as well
FILE *out = fopen(output_filename, "w");
// add error checking here as well
...
So you had a couple of problems x and y are not being assigned correctly, if you harcode argv[1] instead of argv[x] and argv[3] instead of argv[y] it works fine, strangely enough the segfault only occours if the file to write already exists.
so try: code sample
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *);
int see_more();
int main(int argc, char *argv[]) // ./main file.txt -o out.txt
{
FILE *fp;
int i;
int loc;
int x;
int y;
char buffer[LINELEN];
FILE *t;
FILE *out;
FILE *f; // <-- changed to avoid confusion
for(i=1; i<argc; i++){
if(strcmp(argv[i], "-o") == 0)
loc = i;
else if((t = fopen(argv[i], "r")) != NULL){
x = i;
fclose(t);
}
else{
y = i;
}
}
if(loc != -1){
printf("1");
f = fopen(argv[1], "r");// <-- argument 2
printf("2");
out = fopen(argv[3], "w");// <-- argument 4
printf("3");
while(fgets(buffer, LINELEN, f)){
printf("4");
fputs(buffer, out);
}
printf("5");
fclose(f);
fclose(out);
}
}
Since your arguments don't seem to change you can leave it like that or, if you'd like, correct the argument selection for opening.
The getopt mentioned in the comments is always a good option for this.
You still have to account for the errors when the argument input is incorrect, this will still cause errors, but I will leave that for you.
How I can read a text file with comma separated hex values e.g. 0x58,0xA9,0x00 and put its values as elements of an array e.g. LR0
I need to replace this hard-coded with reading from the file:
const unsigned char LR0[] = {0x58,0xA9,0x00}
Here is what I wrote so far. printf("%c", ch); shows me what I need but when I uncomment strcat(LR0, ch); it fails at run time with a segment fault. I don't know if I should use strcat or anything else to append the elements of this LR0 array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int ch;
FILE *fp;
//const unsigned char LR0 [1024] = "";
const unsigned char LR0 [] = {};
fp = fopen("test.txt", "r");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(fp)) != EOF){
printf("%c", ch);
//strcat(LR0, (char) ch);
}
fclose(fp);
return 0;
}
Sorry so basic question not able to fix it by googling etc. I am not a C developer and I am using gcc on linux. My text file does not contain lines so I cannot use this solution
There are two problems in your code.
LR0 is declared as const with unspecified size which is just pointer, writing to it may result in UB.
strcat needs it arguments as char * type but your second argument is of char type (int ch;).
strcat(LR0, (char) ch)
You can use the fscanf with , as delimiter as below to read only the hex values discarding ,.
int main() {
FILE *fp;
unsigned char LR0 [1024] = {};
fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
int i = 0;
while(fscanf(fp, "%c,", &LR0[i]) == 1){
printf("%c", LR0[i++]);
}
fclose(fp);
return 0;
}
const unsigned char LR0 [] = {}; implies a zero length array - that is not standard C yet allowed with some compilers.
strcat(LR0, (char) ch); attempts to 1) write to a const array LR0 and 2) write outside the array - it is only 0 length. Both of the are undefined behavior (UB).
I don't know if I should use strcat
Using str...() functions will not well handle input which may contain many "0x00, 0x00, ...".
How I can read a text file with comma separated hex values e.g. 0x58,0xA9,0x00 and put its values as elements of an array (?)
Read the file to determine its length and contents. I suggest a pass for each.
The below is untested, yet hopefully enough to get OP started. It has little error detection.
// Parse a text file like "0x58,0xA9,0x00"
// Return byte count. Return 0 on error.
size_t read_comma_hex(FILE *f, unsigned char *dest, size_t num) {
rewind(f);
size_t i;
for (i = 0; i<num; i++) {
if (i) {
int ch = fgetc(f);
// Add to tolerate white space before the ',' or after the the last number
while (isspace(ch)) {
ch = fgetc(f);
}
if (ch == EOF) break; // no more data
if (ch != ',') return 0; // Fail, as ',' expected
}
unsigned char hex;
if (fscanf(f, "0x%hhx", &hex) != 1) return 0;
if (dest) dest[i] = hex;
}
return i;
}
void read_comma_hex_file(FILE *f) {
size_t n = read_comma_hex(f, NULL, SIZE_MAX);
if (n == 0) return; // no data or failure
// OP wants an array - research variable length array
const unsigned char LR0[n];
// Alternative: allocate memory instead of using an _array_. (not shown)
// Read data into the array
read_comma_hex(f, LR0, n);
// use LR0 and n some how
for (size_t i = 0; i<n; i++) {
printf("0x%02hhX%s", LR0[i], i > 0 ? "," : "");
}
}
When I compile my code, I get no errors. However, when I attempt to run it, I get a segmentation fault (core dumped). Here is my main:
Original code
void main(int argc, char *argv[]){
if(argc < 3){
return;
}
char *stop_list_name = argv[1];
char *doc_names[argc - 2];
int i;
for(i = 0; i < argc; i++){
doc_names[i] = argv[i];
}
//create the array of stop words
char *stopWords[50];
char *word;
int word_counter = 0;
FILE *fp;
fp = fopen(stop_list_name, "r");
if(fp != NULL){
while(!feof(fp)){
fscanf(fp, "%s", word);
stopWords[word_counter] = word;
word_counter++;
}
}
fclose(fp);
for(i = 0; stopWords[i] != '\0'; i++){
printf("%s", stopWords[i]);
}
}
I'm pretty sure something is wrong in my while loop, but I don't exactly know what, or how to fix it.
Amended code
After seeing the answers, I modified my code so it looks like this, but it still crashes. What's wrong now?
int main(int argc, char *argv[]){
if(argc < 3){
return;
}
char *stop_list_name = argv[1];
char *doc_names[argc - 2];
int i;
for(i = 2; i < argc; i++){
doc_names[i-2] = argv[i];
}
//create the array of stop words
enum {MAX_STOP_WORDS = 50};
char *stopWords[MAX_STOP_WORDS];
int word_counter = 0;
FILE *fp = fopen(stop_list_name, "r");
if(fp != NULL){
char word[64];
int i;
for(i = 0; i < MAX_STOP_WORDS && fscanf(fp, "%63s", word) == 1; i++){
stopWords[i] = strdup(word);
}
word_counter = i;
fclose(fp);
}
for(i = 0; stopWords[i] != '\0'; i++){
printf("%s", stopWords[i]);
}
}
Problems in the original code
One possible source of problems is:
char *doc_names[argc - 2];
int i;
for(i = 0; i < argc; i++){
doc_names[i] = argv[i];
}
You allocate space for argc-2 pointers and proceed to copy argc pointers into that space. That's a buffer overflow (in this case, a stack overflow too). It can easily cause the trouble. A plausible fix is:
for (i = 2; i < argv; i++)
doc_names[i-2] = argv[i];
However, you really don't need to copy the argument list; you can just process the arguments from index 2 to the end. I note that the code shown doesn't actually use doc_names, but the out-of-bounds assignment can still cause trouble.
You are not allocating space to read a word into, nor allocating new space for each stop word, nor do you ensure that you do not overflow the bounds of the array in which you're storing the words.
Consider using:
enum { MAX_STOP_WORDS = 50 };
char *stopWords[MAX_STOP_WORDS];
int word_counter = 0;
FILE *fp = fopen(stop_list_name, "r");
if (fp != NULL)
{
char word[64];
for (i = 0; i < MAX_STOP_WORDS && fscanf(fp, "%63s", word) == 1; i++)
stopWords[i] = strdup(word);
word_counter = i;
fclose(fp);
}
This diagnosed problem is definitely a plausible cause of your crash. I used i (declared earlier in the code) in the loop because word_counter makes the loop control line too long for SO.
Strictly, strdup() is not a part of standard C, but it is a part of POSIX. If you don't have POSIX, you can write your own:
#include <stdlib.h>
#include <string.h>
char *strdup(const char *str)
{
size_t len = strlen(str) + 1;
char *result = malloc(len);
if (result != 0)
memmove(result, str, len);
return result;
}
You also have some other bad practices on display:
while (!feof(file)) is always wrong.
What should main() return in C and C++?
You should only call fclose(fp) if the fopen() worked, so you need to move the fclose() inside the if statement body.
Problems in the amended code
There's one important and a couple of very minor problems in the amended code:
Your loop that prints the stop words depends on a null pointer (curiously spelled as '\0' — it is a valid but unconventional spelling for a null pointer), but the initialization code doesn't set a null pointer.
There are (at least) two options for fixing that:
Add a null pointer:
for (i = 0; i < MAX_STOP_WORDS-1 && fscanf(fp, "%63s", word) == 1; i++)
stopWords[i] = strdup(word);
stopWords[i] = 0;
fclose(fp);
}
for (i = 0; stopWords[i] != '\0'; i++)
printf("%s\n", stopWords[i]);
Note that the upper bound is now MAX_STOP_WORDS - 1.
Or you can use wordCount instead of a condition:
for (i = 0; i < wordCount; i++)
printf("%s\n", stopWords[i]);
I'd choose the second option.
One reason for doing that is it avoids warnings about wordCount being set and not used — a minor problem.
And doc_names is also set but not used.
I worry about those because my default compiler options generate errors for unused variables — so the code doesn't compile until I fix it. That leads to:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc < 3)
{
fprintf(stderr, "Usage: %s stop-words docfile ...\n", argv[0]);
return 1;
}
char *stop_list_name = argv[1];
char *doc_names[argc - 2];
int i;
for (i = 2; i < argc; i++)
{
doc_names[i - 2] = argv[i];
}
int doc_count = argc - 2;
// create the array of stop words
enum { MAX_STOP_WORDS = 50 };
char *stopWords[MAX_STOP_WORDS];
int word_counter = 0;
FILE *fp = fopen(stop_list_name, "r");
if (fp != NULL)
{
char word[64];
int i;
for (i = 0; i < MAX_STOP_WORDS && fscanf(fp, "%63s", word) == 1; i++)
stopWords[i] = strdup(word);
word_counter = i;
fclose(fp);
}
for (i = 0; i < word_counter; i++)
printf("stop word %d: %s\n", i, stopWords[i]);
for (i = 0; i < doc_count; i++)
printf("document %d: %s\n", i, doc_names[i]);
return 0;
}
And, given a stop words file containing:
help
able
may
can
it
should
do
antonym
prozac
and compiling it (source file sw19.c, program sw19) with:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
> -Wold-style-definition -Werror sw19.c -o sw19
and running it as:
$ ./sw19 stopwords /dev/null
stop word 0: help
stop word 1: able
stop word 2: may
stop word 3: can
stop word 4: it
stop word 5: should
stop word 6: do
stop word 7: antonym
stop word 8: prozac
document 0: /dev/null
$
You are trying to store the scanned string to an uninitialized pointer,
fscanf(fp, "%s", word);
and word, is not even initialized.
You could use a static buffer for that, just like this
char word[100];
if (fscanf(fp, "%99s", word) != 1)
word[0] = '\0'; /* ensure that `word' is nul terminated on input error */
Also, while (!feof(fp)) is wrong, because the EOF marker wont be set until fscanf() attempts to read past the end of the file, so the code will iterate one extra time. And in that case you would store the same word twice.
Note that you will also need to allocate space for the array of pointers, maybe there you could use malloc().
Yesterday I already asked a question about the same program(copy content of file in reverse order),
but now I don`t know how to call the second function correctly in the main program.
#include<stdio.h>
#include<string.h>
void reverse(char line[])
{
int i;
int length;
char temp;
if (line == NULL)
return;
length = strlen(line);
for (i = 0 ; i < length / 2 + length % 2 ; ++i)
{
if (line[i] == line[length - i - 1])
continue;
temp = line[i];
line[i] = line[length - i - 1];
line[length - i - 1] = temp;
}
return;
}
char copying(char *src_file, char *dst_file) {
fgets(src_file, sizeof(src_file), stdin); reverse(src_file);
if( (src_file = fopen(src_file, "r")) == NULL )
{
printf("ERROR: Source File %s Failed To Open...\n",src_file);
return(-1);
}
fgets(dst_file, sizeof(dst_file), stdin);
if( (dst_file = fopen(dst_file, "w+")) == NULL )
{
fclose(src_file);
printf("ERROR: Destination File %s Failed To Open...\n",dst_file);
return(-2);
}
int ch;
while( (ch = fgetc(src_file)) != EOF )
{
fputc(ch, dst_file);
}
fclose(src_file);
fclose(dst_file);
return dst_file;
}
int main()
{
char src_file[200], dst_file[200];
printf("Enter Source File Name:\n");
fgets(src_file, sizeof(src_file), stdin);
printf("Enter Destination File Name:\n");
fgets(dst_file, sizeof(dst_file), stdin);
*dst_file = copying(src_file, dst_file);
return 0;
}
Your code is very broken, it wouldn't even compile. Here are some fixes:
char copying(char *src_file, char *dst_file) - You have to specify the datatype of the arguments.
char copying(char *src_file, char *dst_file) { ...} - Dont forget the brackets around your function
You first have to declare the variables src_file and dst_file in main
And don't declare them in your copying function, since they already defined as your arguments
You are returning a char pointer, while the function definition of copying says it is only returning a 'char'.
Now if src_file and dst_file in your main function are allocated char pointers, then you are calling the function correctly.
I didn't go through all your code, so there might be more errors. Try to run the compiler and see what errors you will get.
I am trying to write a program that takes the words from a file, and puts those in a dynamic array. However when I try to run my code the program copies it all except for the spaces. How do I fix this?
This is a test does it work?
But I get the following:
Thisisatestdoesitwork?
char** getWords(char* filename, int* pn){
char** tmp = (char**)malloc( 1000*sizeof(char));
int *temp=(int*)malloc(1000*sizeof(int);
int c;
int counter = 0;
FILE* fileInput = fopen(filename, "r");
if(fileInput == NULL){
return tmp; // return if file open fails
}
while((c=fgetc(fileInput)) != EOF){
result = fscanf(fileInput, "%c", &c); //try to read a character
if(isalpha(c)){ //chararect alphabetical
tmp[counter] = c; // safe int to array
counter ++;
printf("%c", c); fflush(stdout);
}
else{ // if read not succesfull
fscanf(fileInput, ""); // needs to scan anything not a character
}
if(counter > 100){ // to not exceed the array
break;
}
if(feof(fileInput)){ // to check if at the end of the file
break;
}
}
fclose(fileInput); // closing file
*pn = counter;
return tmp;}
My main Function:
int main(int argc, char* argv[]){
int n;
char** a = getWords("opdracht_4_5.c", &n);
if (a != NULL){
puts("gevonden woorden:");
for (int i = 0;i < n; i++){
printf("%3d %s\n",i,a[i]);
}
for (int i = 0;i < n; i++){
free(a);
}
free(a);
}
return (EXIT_SUCCESS);
}
There are quite a few problems with your code. Here's a start:
You don't test the return value of fopen().
You don't test the return value of malloc().
You assign the return value of fgetc() to a variable of type char. Plain char is compatible with either signed char or unsigned char. In order to make a distinction between a character and EOF (which is negative), the fgetc() function returns a character converted to unsigned char (or EOF). You need to test for EOF and then convert the value to a plain char.
The is...() function expects an int argument whose value is in the range of an unsigned char or EOF. If you have a plain char, you first have to cast it to unsigned char, or you can pass the return value of fgetc() straight to isalpha().
You attempt to append an zero-length char array (temp) to an uninitialized char array (s), and you do not test if there is enough room in the target array. This is broken for more reasons than than I care to enumerate.
You allocate memory for an array of 1000 pointers to char, but you never allocate memory for the char pointers themselves.
You try to append your buffer (s) to an uninitialized pointer (*tmp).
You call strlen() on something that is not null-terminated.
You never return the length of the array.
You call a number of functions that have not been declared.
This will read the file, put each word in an array
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
char** getWords(char* filename, int* pn){
char input[100]; // array to hold each word
char** tmp; // double pointer
int counter = 0;
int words = 0;
int c;
tmp = malloc( (*pn)*sizeof(char*)); // allocate pointers for number of words
if ( tmp == NULL) {
printf ( "malloc failed\n");
exit (1);
}
FILE* fileInput = fopen(filename, "r");
if(fileInput == NULL){
printf ( "file open failed\n");
*pn = 0; // no words entered
return tmp; // return if file open fails
}
while(( c = fgetc(fileInput)) != EOF){
if( isalnum(c)){ // is alpha or number
input[counter] = c; // save to array
input[counter + 1] = '\0'; // save a \0 to the end to make a string
counter ++;
}
else{ // not alpha or number
if ( counter > 0) { // if there are characters, save the word
tmp[words] = malloc ( strlen ( input) + 1); // memory for this word
strcpy ( tmp[words], input); // copy the word to the array
words++;
counter = 0;
if ( words >= *pn) { // got all the words wanted
break;
}
}
}
if(counter > 98){ // too many characters for input, start a new word
tmp[words] = malloc ( strlen ( input) + 1);
strcpy ( tmp[words], input);
words++;
counter = 0;
if ( words >= *pn) {
break;
}
}
}
fclose(fileInput); // closing file
*pn = words; // save number of words
return tmp;
}
int main(int argc, char* argv[]){
int n;
int i;
printf ( "enter the number of words to obtain\n");
scanf ( "%d", &n);
char** a = getWords("opdracht_4_5.c", &n);
if (a != NULL){
puts("gevonden woorden:");
for ( i = 0;i < n; i++){
printf("%3d %s\n",i,a[i]);
}
for ( i = 0;i < n; i++){
free(a[i]); // free each word
}
free(a); // free the pointer to the words
}
return (EXIT_SUCCESS);
}
The input file I used had these as the first two lines
#include<stdio.h>
#include<string.h>
I get this output:
enter the number of words to obtain
6
gevonden woorden:
0 include
1 stdio
2 h
3 include
4 string
5 h
This answer is as yet incomplete
Please allow me to finish this before commenting on it -- Thank you
There are a lot if issues with your code, I won't clean it up for you. However I would like to give you some hints on how your program SHOULD be coded:
Your main objective is to read a file and load the content word by word in an array.
Sorting is an incorrect use because that implies you want to sort them alphabetically or in some other order after loading it into an array.
Okay, so first things first, let's figure out the overall operation of our program. We'll call our program kitten, because it's not quite as powerful as cat.
To run our program we will assume that we give it the filename we want to read on the command-line as follows:
$ ./kitten somefile.txt
and expect the output to be:
word1
word2
word3
.
.
.
wordN
Total words: N
So, let's get started, first we make sure that our user specifies a filename:
#include <stdio.h>
int usage(const char *progname);
int main(int argc, char *argv[])
{
if (argc < 2) {
usage(argv[0]);
return -1;
}
return 0;
}
int usage(const char *progname)
{
fprintf(stderr, "Usage is:\n\t%s filename\n", progname);
}
Now that we know that our program can get a filename, let's try to open the text file, if there is an issue with it we use perror to display the error and exit the program, otherwise we are ready to use the file:
#include <stdio.h>
#include <errno.h>
int usage(const char *progname);
int main(int argc, char *argv[])
{
FILE *fp;
if (argc < 2) {
usage(argv[0]);
return -1;
}
fp = fopen(argv[1], "r");
if (!fp) {
perror(argv[1]); /* display system error, with the filename */
return -1;
}
/* TODO: file manipulation goes here */
fclose(fp); /* close the file */
return 0;
}
int usage(const char *progname)
{
fprintf(stderr, "Usage is:\n\t%s filename\n", progname);
}
Now in C each function should perform just one task. The task should make human sense. For example if the function is supposed to read words into an array, then that's all it should do, it should not open a file or close a file, which is WHY the code above does not create a function for opening the file the way you did. Your function should take in FILE * as the file to read.
Because we use the FILE * as input we'll start the function name with an f to keep with the stdio convention. Ideally, the function should take a pointer to char * (strings) to store the words in.
#include <stdio.h>
#include <errno.h>
int usage(const char *progname);
size_t fload(FILE *fp, char **wordlist_p);
int main(int argc, char *argv[])
{
FILE *fp;
if (argc < 2) {
usage(argv[0]);
return -1;
}
fp = fopen(argv[1], "r");
if (!fp) {
perror(argv[1]); /* display system error, with the filename */
return -1;
}
if(fload(fp, wordlist_p) < 0) {
fprintf(stderr, "Something went wrong\n")
}
fclose(fp); /* close the file */
return 0;
}
int usage(const char *progname)
{
fprintf(stderr, "Usage is:\n\t%s filename\n", progname);
}
size_t fload(FILE *fp, char **wordlist_p)
{
size_t rv = -1; /* return value */
return rv;
}
Now we run into a conceptual problem. How do we allocate memory for wordlist_p? I mean we don't have any idea about how big the file is, we also don't know how big the biggest word in the file is.
Crude approach
Let's first try an think about it the simple way:
Point to the beginning of the `wordlist_p` with a `tail_pointer`
Read the file line by line, (we assume no hyphenation)
For each line split the line up along white spaces,
Allocate space for the number of words in the `wordlist_p` array
For each word in the split line
Allocate space for the word itself
Save the pointer to the word at the tail_pointer
Advance wordlist_p tail_pointer
Next word
Next Line
Let's look at what the fload function would look like with these steps above,
More to come ##