将文件指针复制到数组中

时间:2017-07-21 20:38:37

标签: c arrays

在这里,我试图从文本文件中读取,将此文件复制到一个数组中,然后我想将该数组写入另一个文本文件。这根本不是复制到数组中。我打印时只是得到空白值。

filter component

1 个答案:

答案 0 :(得分:0)

工作代码。希望这变得更清楚:) 请注意,您正在使用fread / fwrite - 与字符串的fgets / fputs进行比较。

#include "stdio.h"
#include "string.h"

#define BUFSIZE 50
// memory size 'plus one' to leave room for a string-terminating '\0'
#define BUFMEMSIZE (BUFSIZE+1)

const char *file1 = "hello_world.txt";
const char *file2 = "copyhello.txt";

int main(void)
    {
    char char_array[BUFMEMSIZE];
    char copied_array[BUFMEMSIZE];
    FILE *fInput, *fOutput;

    fInput = fopen(file1, "r");
    if(fInput != NULL)
        {
        fOutput = fopen(file2, "w");
        if(fOutput != NULL)
            {
            // make sure memory is wiped before use
            memset(char_array, 0, BUFMEMSIZE);
            memset(copied_array, 0, BUFMEMSIZE);
            size_t lastSuccessfulRead = 0;
            // the read-then-loop pattern: try and read 50 chars
            size_t bytesRead = fread(char_array, sizeof(char), BUFSIZE, fInput);
            while(bytesRead != 0)
                {
                // we got at least 1 char ..
                // (to be used at end - so we know where in char_array is the last byte read)
                lastSuccessfulRead = bytesRead;
                // 'bytesRead' bytes were read : copy to other array
                strncpy(copied_array, char_array, bytesRead);
                // write to output file, number of bytes read
                fwrite(copied_array, sizeof(char), bytesRead, fOutput);
                // read more, and loop, see if we got any more chars
                bytesRead = fread(char_array, sizeof(char), BUFSIZE, fInput);
                }
            // set char after the last-read-in char to null, as a string-terminator.
            char_array[lastSuccessfulRead] = '\0';
            // an array of chars is also a 'string'
            printf("char_array:   %s\n", char_array);
            fclose(fOutput);
            }
        else printf("cant open %s\n", file2);
        fclose(fInput);
        }
    else printf("cant open %s\n", file1);
    }