2016-03-26 28 views
1

我正在尝试读取文件。我想从文件中读取每行,并检查该行是否有拼写错误。如何清空Char数组并在C中重用它?

为此,我添加了一个条件,即文件中的数据将存储在缓冲区中,直到它获得新的行字符'\n'。获得这一行后,我想清空缓冲区,并重新插入值。我使用了相同的

代码如下:

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

#define W_COUNT 23800 
#define MAX_LEN 100 

char *dict[W_COUNT]; 
char buffer[MAX_LEN]; 
int num_words;  //No of Words 
char *statement[W_COUNT]; 
char buffer1[MAX_LEN]; 

void read_dictionary(); 
void file_read(char *); 
void spell_check(); 
int word_search(char*); 

int main(int argc, char*argv[]){ 
    int i; 
    if(argc < 2){ 
    printf("Expected Filename.\n"); 
    exit(0); 
    } 
    read_dictionary(); 
    file_read(argv[1]); 
// spell_check(); 
} 

void read_dictionary(){ 
    FILE *fd; 
    int i = 0; 
    fd = fopen("dictionary", "r"); 
    while (fscanf(fd,"%s",buffer) != EOF) 
    dict[i++] = strdup(buffer); 
    num_words = i; 
    fclose(fd); 
} 

void file_read(char *filename){ 
    FILE *fd; 
    int i = 0; 
    char c; 
    fd = fopen(filename,"r"); 
    /*while (fscanf(fd,"%s",buffer1) != EOF) 
    { 
    word[i++] = strdup(buffer1); 
    printf("File : %s\n", buffer1); 
    }*/ 
    while ((c = fgetc(fd)) != EOF) 
    { 
    buffer1[i++] = tolower(c); 
    if (c == '\n') 
    { 
     //printf("New Line\n"); 
     spell_check(); 
     buffer1[i] = 0; 

    } 
    //buffer1[i] = 0; 
    } 
    printf("Statement : %s\n", buffer1); 
    fclose(fd); 
} 

void spell_check(){ 
    char *str; 
    str = strtok(buffer1," .?,!-"); 
    while(str != NULL){ 
    if(!word_search(str)) 
    printf("%s Not found.\n",str); 
    str = strtok(0," .?,!-"); 
    } 
} 

int word_search(char *word){ 

    int high, low, mid; 
    high = num_words - 1; 
    low = 0; 
    int found = 0; 

    while (found == 0){ 
    mid = (low + high)/2; 
    if(strcmp(word, dict[mid]) == 0) 
    return 1; 
    else if(strcmp(word,dict[mid]) < 0) 
    high = mid - 1; 
    else 
    low = mid + 1; 
    if (low > high) 
    return 0; 
    } 
} 

任何建议将不胜感激。 预先感谢您。

+0

您可以将空字符分配给缓冲区的起始位置。 –

+0

我试过但没有工作。它只通过第一行循环。 –

+0

在编码中分配空字符的位置? –

回答

2
while ((c = fgetc(fd)) != EOF) 
    { 
    buffer1[i++] = tolower(c); 
    if (c == '\n') 
    { 
     //printf("New Line\n"); 
     spell_check(); 
     i = 0; 
     buffer1[i] = 0; 

    } 
    //buffer1[i] = 0; 
    } 

对于每行读数,您必须将0赋值给i。之后,您必须将空值分配给缓冲区中的第0个位置。 你可以尝试上面的代码循环它将工作。

+0

谢谢你的帮助.. –