Reputation: 55
I have a text file with a list of words, one on each line, and I am supposed to store them in an array and then sort them in alphabetical order. I am stuck and I need some guidance. The only error I get is 730 segment fault
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *data[45];
int i;
int j;
// OPENS THE FILE
FILE *fp = fopen("/classes/cs3304/cs330432/Programs/StringerTest/TestInput.txt", "r");
if (fp == NULL) {
printf("Unable to open the file\n");
} else {
while (fscanf(fp, "%s", data) == 1)
printf("%s\n", data);
fclose(fp);
}
char temp[100];
for (i = 0; i < 45 - 1; i++) {
for (j = j + 1; j < 45; j++) {
if (strcmp(data[i], data[j]) > 0) {
strcpy(temp, data[i]);
strcpy(data[i], data[j]);
strcpy(data[j], temp);
}
}
}
for (i = 0; i < 45; i++) {
printf("%s", data[i]);
}
return (0);
}
Upvotes: 0
Views: 102
Reputation: 460
The code works now. Compare source files to be sure to find all differences. Major aspects: Memory needs to be allocated for data (not only pointer). In practice you need to find out, how much memory needs to be allocated. If you fscanf file to data, then read it into data[i] not into data. Do not just use "45" here. I added variable "num" to store number of words. Then, you need to use "num" also in the loops, and compare "for(j=i+1;j<num;j++)" (it is j=i+1). The rest was okay.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char data[45][45];
int i;
int j;
int num;
// OPENS THE FILE
FILE *fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("Unable to open the file\n");
}
else
{
i=0;
while(fscanf(fp, "%s", data[i]) == 1 )
{
i++;
}
num=i;
}
fclose(fp);
char temp[100];
for ( i=0;i<num-1;i++)
{
for(j=i+1;j<num;j++)
{
if(strcmp (data[i], data[j]) > 0)
{
strcpy(temp,data[i]);
strcpy(data[i], data[j]);
strcpy(data[j], temp);
}
}
}
for (i=0;i<num;i++)
{
printf("%s ", data[i]);
}
// BEGIN: write to file.txt (as asked in comment)
fp = fopen ("file.txt", "w+");
if(fp==NULL) return 1;
for (i=0;i<num;i++)
{
fprintf(fp,"%s ", data[i]);
}
fclose(fp);
// END: write to file.txt (as asked in comment)
return (0);
}
Test of the code:
$ cat test.txt
just a text to test this code
$ ./a.out
a code just test text this to
Upvotes: 2