gpt4 book ai didi

c - 我正在用 C 创建程序来计算已创建文件中的单词数,并按字母顺序将单词保存在新文件中

转载 作者:行者123 更新时间:2023-11-30 14:33:22 25 4
gpt4 key购买 nike

我是大学一年级的初学者,正在学习编程。我已经创建了计算单词数的代码,但我坚持如何将它们按字母顺序排序并将它们写入新文件。以下是我的代码:

#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 等),但我没有这样做,以便使代码尽可能简单

关于c - 我正在用 C 创建程序来计算已创建文件中的单词数,并按字母顺序将单词保存在新文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59373719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com