Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c - How can I read a txt file to an array and sorting in ascending order?

I have a txt file includes 10000 passwords in it.I am trying to sort the passwords by length.Here is my function:

void bubbleSortASC(){
    int n = 9999;
    int i,j ;
    char pw[n];
    char temp;
    FILE* fp;
    fp = fopen("C:\Users\inanm\Desktop\project-work-2018555459\10-million-password-list-top\10000.txt", "r");
    //fgets(pw, n , fp);
    while(!feof(fp)){
        fgets(pw, n , fp);
       //printf("%s",pw);
    }
    for(i = 0; i < n-1;i++) {
        for(j = i+1; j < n; j++){
            if(strlen(pw[i]) > strlen(pw[j])){
                strcpy(temp,pw[i]);
                strcpy(pw[i],pw[j]);
                strcpy(pw[j],temp);
            }
        }
    }
    fclose(fp);
printf("Ascending order of first 10 passwords are : 
");
for (i = 0; i < 10; i++){
        printf("%s ", pw[i]);
    }
     printf("
");
        
}

I've got no error but my output is empty.Can you help me to find the problem

question from:https://stackoverflow.com/questions/65871911/how-can-i-read-a-txt-file-to-an-array-and-sorting-in-ascending-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This would do


void bubbleSortASC() {
    const int lines = 9999;     //< number of words in the file
    const int max_width = 128;  //< max width of a word

    char pw[lines][max_width];  //< array of words

    FILE* fp;
    fp = fopen("words.txt", "r");
    int curr = 0;
    while (!feof(fp)) {
        fgets(pw[curr++], max_width, fp);
    }
    fclose(fp);

    char* sorted[lines];        //< array of char* will be in a sorted order
    for (int i = 0; i < lines; i++) sorted[i] = pw[i];

    // the bubble sort
    for (int i = 0; i < lines - 1; i++) {
        for (int j = 0; j < lines - i - 1; j++) {
            if (strlen(sorted[j]) > strlen(sorted[j+1])) {
                char* tmp = sorted[j];
                sorted[j] = sorted[j+1];
                sorted[j+1] = tmp;
            }
        }
    }

    printf("Ascending order of first 10 passwords are : 
");
    for (int i = 0; i < 10; i++) {
        printf("%s", sorted[i]);
    }
    printf("
");

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...