2013-04-13 58 views
0

嗨,大家好,我正在第二個週末試圖找到解決這個問題的方法。我是c編程新手,我一直試圖讀取文本文件的每一行,並將它們傳遞給自己的變量,在那裏我可以操縱它們(比如比較它們,計算等)。如何將文本文件的每一行讀入自己的變量

我有一個代碼,閱讀每行,但我不能確定如何通過每行一個變量,這裏是代碼:

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

struct line_reader { 
FILE *f; 
char *buf; 
size_t siz; 
}; 


void 
lr_init(struct line_reader *lr, FILE *f) 
{ 
lr->f = f; 
lr->buf = NULL; 
lr->siz = 0; 
} 

char * 
next_line(struct line_reader *lr, size_t *len) 
{ 
size_t newsiz; 
int c; 
char *newbuf; 

*len = 0; 
for (;;) { 
    c = fgetc(lr->f); 
    if (ferror(lr->f)) 
     return NULL; 

    if (c == EOF) { 

     if (*len == 0) 
      return NULL; 
     else 
      return lr->buf; 
    } else { 

     if (*len == lr->siz) { 

      newsiz = lr->siz + 4096; 
      newbuf = realloc(lr->buf, newsiz); 
      if (newbuf == NULL) 
       return NULL; 
      lr->buf = newbuf; 
      lr->siz = newsiz; 
     } 
     lr->buf[(*len)++] = c; 


     if (c == '\n') 
      return lr->buf; 
     } 
     } 
     } 


void 
lr_free(struct line_reader *lr) 
{ 
free(lr->buf); 
lr->buf = NULL; 
lr->siz = 0; 

}

int 
main() 
{ 
struct line_reader lr; 
FILE *f; 
size_t len; 
char *line; 

f = fopen("file.txt", "r"); 
if (f == NULL) { 
    perror("foobar.txt"); 
    exit(1); 
} 


lr_init(&lr, f); 
while (line = next_line(&lr, &len)) { 

    fputs("1: ", stdout); 
    fwrite(line, len, 1, stdout); 
} 
if (!feof(f)) { 
    perror("next_line"); 
    exit(1); 
} 
lr_free(&lr); 

return 0; 

}

任何幫助,將不勝感激。

回答

0

怎麼樣使用數組只是作爲一個建議

如)

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

char** readFile(const char *filename, size_t *lineCount){ 
    FILE *fp; 
    char buff[4096]; 
    size_t lines = 0, capacity=1024; 
    char **line; 

    if(NULL==(fp=fopen(filename, "r"))){ 
     perror("file can't open."); 
     return NULL; 
    } 
    if(NULL==(line=(char**)malloc(sizeof(char*)*capacity))){ 
     perror("can't memory allocate."); 
     fclose(fp); 
     return NULL; 
    } 
    while(NULL!=fgets(buff, sizeof(buff), fp)){ 
     line[lines++] = strdup(buff); 
     if(lines == capacity){ 
      capacity += 32; 
      if(NULL==(line=(char**)realloc(line, sizeof(char*)*capacity))){ 
       perror("can't memory allocate."); 
       fclose(fp); 
       return NULL; 
      } 
     } 
    } 
    *lineCount = lines; 
    fclose(fp); 

    return (char**)realloc(line, sizeof(char*)*lines); 
} 
void freeMem(char** p, size_t size){ 
    size_t i; 

    if(p==NULL) return; 

    for(i=0;i<size;++i) 
     free(p[i]); 
    free(p); 
} 

int main(){ 
    size_t lines; 
    char **line; 

    if(NULL!=(line=readFile("file.txt", &lines))){//lines: set line count of file 
     printf("%s", line[25]);// 26th line of file, zero origin 
    } 
    freeMem(line, lines); 
    return 0; 
} 
0

在任何兼容POSIX的系統只需使用m掃描修改:

for (char *line, nl; scanf("%m[^\n]%c",&line,&nl) != EOF ; free(line)) { 
    if (!line) 
     strcpy(line=malloc(1),""), getchar(); 
    // ... 
} 

m一直在現在五年的標準。

相關問題