c - 我想将输入文件复制到输出文件。

标签 c

在这段代码中,我在我的 open_file 函数中打开了我的文件。然后 process_file 函数需要从我的 in 文件中复制文本并将其复制到 out 文件中。现在它生成一个新文件,但它是空白的。它没有给我任何错误信息。我不知道出了什么问题。

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

#define MAX_LEN 100

FILE* open_file(char prompt[], char mode[]);
FILE* process_file(FILE* in, FILE* out);

int main(int argc, const char * argv[]) {
    FILE* in = NULL;
    FILE* out = NULL;

    printf("MAD-LIBS Text Processor\n");
    printf("The Program will open a mad-libs file, ask you to fill various words, and produce a funny story.\n");

    open_file("Enter mad-lib file name:\n", "r");
    open_file("Enter file name for resulting story:\n", "w");
    process_file(in, out);

    fclose(in);
    fclose(out);
    return 0;
}
/* open_file = prompts user for file name & and attempts to open it, if it fails it prompts the user again. */
FILE* open_file(char prompt [], char mode[]) {
    char filename[255];
    FILE* in;

    do {
        printf("%s", prompt);
        scanf("%s", filename);

        in = fopen(filename, mode);

        if (in == NULL) {
            printf("Unable to open file: %s. Try Again!\n", filename);
        }
    } while(in == NULL);
    return in;
}
/* process_file = processes entire input file and writes it to output file */
FILE* process_file(FILE* in, FILE* out) {
    char content[MAX_LEN];
    char NewContent[MAX_LEN];
    //gets whats in file in
    while(fgets(content, content[MAX_LEN], in) != NULL) {
        fputs (content, stdout);
        strcat(NewContent, content);
    }
    // copies it 
    while (fgets(content, content[MAX_LEN], in) != NULL) {
        fprintf(out, "%s", content);
    }
    printf("Successfully copied file\n");
    return in;
}

最佳答案

您永远不会将 open_file 函数中的 FILE* 分配给您的变量,因此它永远不会被处理。

in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");

关于c - 我想将输入文件复制到输出文件。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49290527/

相关文章:

C: 'unlink' 未在此范围内声明

c - 在哪里可以找到 execve() 的源代码?

c - MS VS formatstring 用 $ 指定使用的参数

c - 如何将两个 gmpz_t 转换为一个 mpq_t?

c - 有没有办法将 fd 转换为 FILE* 或者是否有返回 FILE* 的 mkstemp 版本?

c - 每个连续子数组的最大值

c++ - 如何将 NDEF 中的 NFC 标签转换为非 NDEF

c - 如何将数字表示为 15 位宽的字段?

c - 可以使用 fscanf 读取直到 EOF 吗? C

c - 删除 Flash NOR : ioctl(MEMUNLOCK) return status?