2011-12-21 10 views
1

ファイルを開き、すべての行を動的に割り当てられた文字列に読み込み、最初の4行を出力するには、ANSI Cで必要です。このファイルのサイズは2^31-1バイトまでで、各行は最大16文字です。私は、次のを持って、動作していないよう:ファイルからダイナミックアレイに行を保存して印刷する方法は?

#define BUFSIZE 1024 
char **arr_lines; 
char buf_file[BUFSIZE], buf_line[16]; 
int num_lines = 0; 
// open file 
FILE *fp = fopen("file.txt", "r"); 
if (fp == NULL) { 
    printf("Error opening file.\n"); 
    return -1; 
} 
// get number of lines; from http://stackoverflow.com/a/3837983 
while (fgets(buf_file, BUFSIZE, fp)) 
    if (!(strlen(buf_file) == BUFSIZE-1 && buf_file[BUFSIZE-2] != '\n')) 
     num_lines++; 
// allocate memory 
(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char)); 
// read lines 
rewind(fp); 
num_lines = 0; 
while (!feof(fp)) { 
    fscanf(fp, "%s", buf_line); 
    strcpy(arr_lines[num_lines], buf_line); 
    num_lines++; 
} 
// print first four lines 
printf("%s\n%s\n%s\n%s\n", arr_lines[0], arr_lines[1], arr_lines[2], arr_lines[3]); 
// finish 
fclose(fp); 

私はこれに書き込むために、簡単にその要素にアクセスするためにarr_linesを定義する方法の問題を抱えています。

+0

を開始として、mallocの結果をキャストしないでください(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-mallocを参照)。第二に、コンパイルする完全な最小限のプログラムを投稿して、あなたが経験している問題を紹介します... –

答えて

0

変更

(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char)); 

arr_lines = malloc(num_lines * sizeof(char*)); 

に、それ以下のwhileループでは、あなたのコード内のいくつかの問題があり

arr_lines[n] = malloc(16 * sizeof(char)); 
3

追加しますが、主なものですmalloc行では、初期化されていないポインタの参照を外しています。また、行が1つの単語で構成されている場合を除き、fscanf(...%s ...)の代わりにfgets()を使用してください。たとえあなたの行が単語であっても、あなたが行を数えたのと同じ種類のループを使う方が安全です。そうしないと、割り当てられた行よりも多くの行を読む危険があります。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(void){ 
#define LINESIZE 16 
     char *arr_lines, *line; 
     char buf_line[LINESIZE]; 
     int num_lines = 0; 
     // open file 
     FILE *fp = fopen("file.txt", "r"); 
     if (fp == NULL) { 
       printf("Error opening file.\n"); 
       return -1; 
     } 
     // get number of lines; from http://stackoverflow.com/a/3837983 
     while (fgets(buf_line, LINESIZE, fp)) 
       if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n')) 
         num_lines++; 
     // allocate memory 
     arr_lines = (char*)malloc(num_lines * 16 * sizeof(char)); 
     // read lines 
     rewind(fp); 
     num_lines = 0; 
     line=arr_lines; 
     while (fgets(line, LINESIZE, fp)) 
       if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n')) 
         line += LINESIZE; 
     // print first four lines 
     printf("%s\n%s\n%s\n%s\n", &arr_lines[16*0], &arr_lines[16*1], &arr_lines[16*2], &arr_lines[16*3]); 
     // finish 
     fclose(fp); 
     return 0; 
} 

関連する問題