我想获取一个输入文件并从中创建索引并将其保存为另一个文件。
当我将输入文件重定向到我的程序
时,一切正常./myprog <text.txt
但是当我尝试使用argv [1]从命令行打开文件作为参数时,它无法正常工作,我无法理解为什么
我猜它是如何打开我的文件的
发布整个代码,但我想当我读取文件
时问题出现在代码的顶部#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXW 1000
#define MAXC 100
typedef struct {
char seen[MAXC];
char lines[1024];
} wfstruct;
int get_word_freq (wfstruct *words, size_t *idx, FILE *fp);
int compare (const void *a, const void *b);
int main (int argc, char **argv) {
printf("%d",argc);
printf("%s",argv[1]);
/* initialize variables & open file or stdin for seening */
wfstruct words[MAXW] = {{{ 0 }, 0}};
size_t i, idx = 0;
FILE *fp2;
if(argc>2)
{
printf("too much args\n");
return 1;
}
if(argc<2)
{
printf("give me a file\n");
return 1;
}
FILE *fp=fopen(argv[1],"r");
get_word_freq (words, &idx, fp);
/* sort words alphabetically */
qsort (words, idx, sizeof *words, compare);
fp2 = fopen("Output.txt", "w");
fprintf(fp2, "The occurences of words are");
printf ("\nthe occurrence of words are:\n\n");
for (i = 0; i < idx; i++)
{
fprintf(fp2, " %-28s : seen in lines %s \n", words[i].seen, words[i].lines);
printf (" %-28s : seen in lines %s \n", words[i].seen, words[i].lines);
}
fclose(fp2);
return 0;
}
int get_word_freq (wfstruct *words, size_t *idx, FILE *fp)
{
size_t i;
/* read each word in file */
char *word;
word = malloc(sizeof(char));
int now;
int line = 1;
int j=0;
for (;;j++)
{
now=getchar();
if(now==EOF)
{
break;
}
if(!isalpha(now)){
word[j] = '\0';
j=-1;
for (i = 0; i < *idx; i++) {
/* if word already 'seen', update 'words[i]. freq' count */
if (strcmp (words[i].seen, word) == 0) {
sprintf(words[i].lines + strlen(words[i].lines),"%d,",line);
goto skipdup; /* skip adding word to 'words[i].seen' */
}
} /* add to 'words[*idx].seen', update words[*idx].freq & '*idx' */
strcpy (words[*idx].seen, word);
sprintf(words[*idx].lines,"%d,",line);
(*idx)++;
skipdup:
if (*idx == MAXW) { /* check 'idx' against MAXW */
fprintf (stderr, "warning: MAXW words exceeded.\n");
break;
}
if(now=='\n'){
line++;
}
continue;
}
now=tolower(now);
word[j]=now;
word=realloc(word,(j+1+1)*sizeof(char));
}
fclose (fp);
return 0;
}
/* qsort compare funciton */
int compare (const void *a, const void *b)
{
wfstruct *ap = (wfstruct *)a;
wfstruct *bp = (wfstruct *)b;
return (strcmp (ap->seen, bp->seen));
}
答案 0 :(得分:1)
首先,请格式化您的代码,然后再使用fopen()打开文件后,尝试使用getchar()读取它。这不会起作用,因为getchar()从stdin读取。要从使用fopen()打开的文件中读取字符,您应该使用fgetc()。
http://www.cplusplus.com/reference/cstdio/fgetc/
在你的函数get_word_freq()中将now=getchar();
更改为
now=fgetc(fp);