gpt4 book ai didi

c - 从文件中读取动态内存

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:09 25 4
gpt4 key购买 nike

我迫切需要一些帮助来完成教授给我的练习。本质上,我正在制作一个使用结构和动态内存的程序,它会读取一个文件,其中每一行都有一个单词,它会将每个唯一的单词以及它在文件中出现的次数打印到一个新文件中。

例如,如果进入的文件有这个

apple
orange
orange

它打印到的文件会说

apple 1
orange 2

到目前为止,这是我的代码

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

struct wordfreq {
int count;
char *word;
};

int main(int argc, char *argv[]){

int i;
char *temp;
FILE *from, *to;
from = fopen("argc[1]","r");
to = fopen("argv[1]","w");

struct wordfreq w1[1000];
struct wordfreq *w1ptr[1000];
for(i = 0; i < 1000; i++)
w1ptr[i] = NULL;
for(i = 0; i < 1000; i++)
w1ptr[i] = (struct wordfreq*)malloc(sizeof(struct wordfreq));

while(fscanf(from,"%256s",temp)>0){

}

for(i = 999; i >= 0; i--)
free(w1ptr[i]);

}

w1ptr 应该将文件中的一个单词存储在 wordfreq 文件中,然后递增该数组中的计数。不过,我不知道如何将单词存储在 *word 中。任何帮助将不胜感激

最佳答案

这就是您从文件中读取/写入的一般方式

const int maxString = 1024; // put this before the main

const char * fn = "test.file"; // file name
const char * str = "This is a literal C-string.\n";

// create/write the file
puts("writing file\n");
FILE * fw = fopen(fn, "w");
for(int i = 0; i < 5; i++) {
fputs(str, fw);
}

fclose(fw);
puts("done.");

// read the file
printf("reading file\n");
char buf[maxString];
FILE * fr = fopen(fn, "r");
while(fgets(buf, maxString, fr)) {
fputs(buf, stdout);
}

fclose(fr);
remove(fn); // to delete a file

puts("done.\n");

关于c - 从文件中读取动态内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554586/

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