Hi, needing help with c programming. Im suppose to make a "poor mans" variation to the Sort function built into unix. The program is suppose to read in a file and sort the contents of the file. So its a variation of the Unix Sort feature. I have remade the readLine function we were provided so that it doesnt use fgets. I need help on where to go from here, Not sure on how to make a sort function. Here are the reqirements of the program:
Code:
• Re-implement the readLine() function so that it no longer makes use of fgets(). Instead,
process the input on a given line character-by-character.
• Provide code which will create a data structure similar to argv to hold all of the words to be
sorted. Use malloc() to ensure that each entry has just the required number of bytes needed
to store the words. The final entry in your array should be the NULL pointer.
• Implement a sort() function which will rearrange the words in sorted order. To swap two
words in your array, note that only a pair of pointers need to move. The strings themselves,
once established, will never move.
Heres what i have:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINES 1000 /* maximum number of reminders */
#define WORD_LENGTH 10 /* max length of reminder message */
int read_line(char str[], int n);
int main(int argc, char *argv[])
{
char *lines[MAX_LINES];
char ch, line = argv[1];
char line[WORD_LENGTH + 1];
bool lineOverflow; /* not enough room in char array? */
int day, i, j, num_lines = 0;
fp = fopen(FILE_NAME, "r");
if (fp == NULL) {
fprintf(stderr, "Error: can't open %s for reading.\n", FILE_NAME);
exit(EXIT_FAILURE);
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "Error: can't open %s for reading.\n", argv[1]);
exit(EXIT_FAILURE);
}
while(readLine(line, sizeof(line), fp, &lineOverflow) != NULL) {
printf("%s", line);
}
fclose(fp);
}
return(0);
}
char *readLine(char *s, int n, FILE *fp, bool *overflow) {
int length;
int ch;
int skipped; /* the number of NON-newline characters skipped over
for lines too long to fit in the given char array */
int i = 0;
ch = getc(fp); /* read a line */
if (ch == EOF) {
*overflow = false;
return NULL; /* either stream is at eof or there was a read error */
}
while(ch != '\n' && i < (n - 1)) {
s[i++] = ch;
ch = getc(fp);
}
/* read was successful: did we get the entire line? */
length = strlen(s);
if (s[length - 1] == '\n') {
s[length - 1] = '\0'; /* we don't want to store the newline */
*overflow = false;
}
else {
/* skip to end of current line */
skipped = 0;
while ((ch = getc(fp)) != '\n' && (ch != EOF))
skipped++;
*overflow = (skipped > 0);
}
return s;
}
void Sort( ) {
}