簡體   English   中英

我正在用 C 創建程序來計算已經創建的文件中的單詞並按字母順序將單詞保存在新文件中

[英]I am creating program in C to count words in file already created and save the words in new file in alphabetical order

我是大學一年級的初學者,學習編程。 我已經創建了計算單詞的代碼,但我一直在思考如何將它們按字母順序排序並將它們寫入一個新文件。 以下是我的代碼:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv)
{   
    char ch;
    FILE *subor;
    int pocet = 0;
    subor = fopen("subor.txt","r");

    while((ch = fgetc(subor)) != EOF){
        if(ch ==' ' || ch == '\n')
            pocet++;
    }

    printf("Pocet slov v subore je: %d", pocet);
    fclose(subor);

    if (argc < 2) return 1;

    char * nazovsuboru = argv[1];
    FILE * fp = fopen(nazovsuboru, "r");
    if (fp == NULL) return 1;

    return 0;
}

你能幫我添加按字母順序保存單詞到新文件的功能嗎?

這里:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define BUFSIZE     1024
#define DEFAULTSIZE 1024


int cmp_strings(const void * a, const void * b)
{
    return strcmp(*(const char **)a, *(const char **)b);
}


int main()
{
    char buffer[BUFSIZE];
    char * token;
    const char * delimiters = " \n,!?"; // add punctuation as necessary
    size_t word_counter = 0, nbytes;
    char * * words = malloc(DEFAULTSIZE * sizeof(char*));

    FILE * inputfile = fopen("filename.txt", "r");
    if (!inputfile) {
        perror("fopen");
        return EXIT_FAILURE;
    }

    while ((nbytes = fread(buffer, 1, BUFSIZE, inputfile)) > 0) {
        buffer[nbytes] = '\0';

        token = strtok(buffer, delimiters);
        while (token) {
            words[word_counter] = malloc((strlen(token)+1) * sizeof(char));
            strcpy(words[word_counter], token);
            word_counter++;
            token = strtok(NULL, delimiters);
        }
    }

    // sorting function from stdlib
    qsort(words, word_counter, sizeof(const char*), cmp_strings);

    FILE * outputfile = fopen("out.txt", "w");

    for (size_t i = 0; i < word_counter; i++) {
        sprintf(buffer, "%s\n", words[i]);
        fwrite(buffer, 1, strlen(buffer), outputfile);
        free(words[i]);
    }
    free(words);

    fclose(inputfile);
    fclose(outputfile);

    return EXIT_SUCCESS;
}

一些注意事項:

  • 我對文件中的字數及其最大大小做了一些假設。 使該程序適應實際情況的練習將留給讀者作為練習 例如,您可以通過使用鏈表或在需要時僅執行realloc來實現此目的
  • 您應該始終檢查函數返回(即malloc等),我沒有這樣做是為了使代碼盡可能簡單

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM