2014-02-13 59 views
0

我想知道是否可以在计算出如何从文件中读入文本到C中的数组中获得一些帮助。我的主要目标是创建一个文本格式化程序将正确的文字,但目前我只是想正确阅读的文字。如何将文本读取到C语言数组中

在此先感谢!

#include<stdlib.h> 
#include<stdio.h> 
#define TEMP 1000 
int main() { 

    int words_in_line = 0; 
    int spaces_to_put = 0; 
    int z; //for loop 
    int i; //for loop 
    int count; //indicates when to put a new line. 
    int k; //for loop 
    int w; //for loop 
    int drop_spaces; //for loop 
    int check; 
    size_t nread; 
    FILE *f_open; 
    char buffer[TEMP]; 

    f_open = fopen("hollow.txt", "r"); 
    char *buf = malloc(TEMP); 

    printf("Enter the length of chars in a line: \n"); 
    scanf("%d", &w); 

    if (buf == NULL) { 
    printf("Buf is null \n"); 
    } 

    while ((nread = fread(buf, 1, TEMP, f_open)) > 0) { //going through the stream. 
    buffer[TEMP] = fwrite(buf, 1, nread, stdout); //need to load the steam into the array. 
    //size_t cannot match char[]. 
    } 
    if (ferror(f_open)) { 
    printf("Error reading file \n"); 
    } 
    return 0; 
} 
+0

只需制作'mmap'文件,然后像使用巨大的字符串变量一样工作。顺便说一句,在你的情况下,你可以简单地用'getline'逐行读取 –

+0

在'strcpy'或'memcpy'上进行阅读。 –

+0

'fwrite()'返回写入的项目数量。 – BLUEPIXY

回答

1

而不是使用fread()/fwrite()阅读文本,使用fgets()阅读和fprintf()自圆其说。

assert(w >= 0); 
while (fgets(buf, TEMP, f_open) != NULL) { 
    // right justify the text 
    fprintf(stdout, "%*s", w + 1, buf); 
} 

+ 1为在buf结束通常\n。需要更多的工作来处理\n不存在的情况。例如文件的最后一行。

相关问题