我想获取一个输入文件并从中创建索引并将其保存到另一个文件。
当我像这样将输入文件重定向到我的程序时,一切正常
./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));
}
最佳答案
首先,请格式化您的代码,其次 - 使用 fopen() 打开文件后,您尝试使用 getchar() 读取它。这是行不通的,因为 getchar() 从 stdin 读取。要从使用 fopen() 打开的文件中读取字符,您应该使用 fgetc()。
http://www.cplusplus.com/reference/cstdio/fgetc/
在函数 get_word_freq() 中将 now=getchar();
更改为
now=fgetc(fp);
关于c - 使用 argv[] 从命令行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44608134/