繁体   English   中英

将两个文件合并到第三个文件会产生乱码

[英]Merging two files into third file gives gibberish

实际上,我正在尝试使用do-while循环将两个文件合并到第三个文件中。 该程序运行良好,但是当我打开第三个文件时,它只包含乱码。

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

int main(void)
{
    FILE *f1 = fopen("file1.txt", "r");
    FILE *f2 = fopen("file2.txt", "r");
    FILE *f3 = fopen("file3.txt", "w");

    if (f1 == NULL || f2 == NULL || f3 == NULL)
    {
        printf("Issue with the files\n");
        exit(0);
    }

    char let;
    printf("File-1\n");

    do
    {
        fputc(let, f3);
        printf("%c", let);
    } while ((let = fgetc(f1)) != EOF);

    printf("\n\nFile-2\n");

    do
    {
        fputc(let, f3);
        printf("%c", let);
    } while ((let = fgetc(f2)) != EOF);
    
    printf("\nTASK COMPLETED!! Files have been merged");

    fclose(f1);
    fclose(f2);
    fclose(f3);
}

文件 3- 胡言乱语:

在此处输入图像描述

但是当我使用while不是do-while ,事情运行良好,第三个文件给出了预期的结果。 我不知道为什么do-while会产生问题。

文件 - 1 的内容:

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

文件 - 2 的内容:

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

使用 do-while 循环是错误的。 但是,如果您想使用它,请进行以下更改。

  1. 将 char char let更改为char let='\0'
  2. 在第一个 while 循环后重新分配let='\0'以清除缓冲区。
  3. 合并 2 个或更多文件时,以 append 模式打开目标文件以避免覆盖。 FILE *f3 = fopen("file3.txt","a");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM