【问题标题】:dynamic memory reading from a file从文件中读取动态内存
【发布时间】:2017-04-22 02:31:13
【问题描述】:

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

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

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 中。任何帮助将不胜感激

【问题讨论】:

  • 你必须先为char *temp;分配内存,然后才能在fscanf中使用它
  • 1) int main(){ --> int main(int argc, char *argv[]){, from = fopen("argc[1]","r"); to = fopen("argv[1]","w"); --> from = fopen(argv[1], "r"); to = fopen(argv[2], "w");
  • @BLUEPIXY 他首先要重新定义 man 之前是main(int argc, char *argv[])
  • 您可能会发现Count the reocurrence of words in text file 很有帮助。

标签: c memory-management struct


【解决方案1】:

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

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");

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2010-10-26
    • 2023-03-23
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多