One thing of possible importance to know beforehand is that, while this program is meant to be run on Linux, I have a Mac to write on and won't be able to get to the computer lab for maybe ten hours.
So I've got a homework problem where, ultimately, I have to sort lines in a text file (including strings and integers) using qsort. The professor wants us to do this by reading the whole file into memory. She even gave us some bits of code to integrate into our program to help us.
I'm stuck on the first part.
Namely, I'm trying to allocate the memory for the file and then read it into an array. To check that it works, I'm trying to print out the array. I've been getting two main error reports, though they may be pointing to the same problem. The first is a warning before I run the program, saying "passing 'const char *' to parameter of type 'char *' discards qualifiers". The second is when my program quits on me with "Segmentation fault: 11".
I feel like I really don't know what I'm doing. Here's my code:
Two parts of this code are basically regurgitated from what the professor told us.Code:#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> int filesize(char * filename) { struct stat status; if (stat(filename, &status) == -1) { return -1; } else { return (int) status.st_size; } } int main(int argc, const char * argv[]) { FILE *read; char in_name; int n = 0; printf("What file should be read?\n"); if (scanf("%s", &in_name) != 1) { printf("Invalid input.\n"); return 1; } read = fopen(&in_name,"r"); if (read == NULL) { printf("Cannot open input file.\n"); return 1; } char * data = malloc(filesize(argv[1])); data[n] = fgetc(read); while (data[n] != EOF) { if (data[n] == '\n') data[n] = '\0'; data[++n] = fgetc(read); } for (int i = 0; i <= n; i++) { printf("%d \n", data[i]); } fclose(read); return 0; }
The first is supposed to help find out how much memory to allocate.
The second, she said:Code:#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> /* returns size of file *filename in bytes, or -1 on error */ int filesize(char * filename) { struct stat status; if (stat(filename, &status) == -1) { return -1; } else { return (int) status.st_size; } }
You can use malloc to get space in memory:Code:char * data = malloc(filesize(argv[1]));
Now you can operate on 'data' like an array -- the first character is data[0], the next one data[1], etc.
This is what the error "passing 'const char *' to parameter of type 'char *' discards qualifiers" is referring to.