SUIYUNZOU 发表于 2021-2-14 14:08:33

c语言的文件问题,哪位大佬过来瞧瞧哈?

本帖最后由 SUIYUNZOU 于 2021-2-15 12:47 编辑

<
#include<stdio.h>
#include<stdlib.h>
int main()
{
        FILE*in , *out;
        char ch,infile, outfile;
        printf("请输入被打开文件的名字");
        scanf("%s",infile);
        printf("请输入要复制文件的名字:");
        scanf("%s",outfile);
       
        if((in=fopen(infile,"r"))==NULL)
        {
        printf("打开文件infile失败\n");
        exit(0);
        }
                if((in=fopen(outfile,"w"))==NULL)
        {
        printf("打开文件outfile失败\n");
        exit(0);
        }
        ch=fgetc(in);
        while(!feof(in))
        //while(ch!=EOF)
        {
                fputc(ch,out);
                putchar(ch);
                ch=fgetc(in);
               
        }
        putchar(10);
        fclose(in);
        fclose(out);
        return 0;
}>
我尝试将电脑file.txt文档复制到新建文件的file2.txt,并且输出,但均为空??
电脑储存了文档file.txt;尝试以写的方式写到file2.txt。但是最后结果如下:
控制台无输出文档内容,且打开新建的文档为空。

C4rB0n 发表于 2021-2-15 17:55:08

第十七行,if((in=fopen(outfile,"w"))==NULL)
你把输出文件付给了输入文件,因为是以w模式打开,所以内容也就空了。
更正后的代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
      FILE*in , *out;
      char ch,infile, outfile;
      printf("请输入被打开文件的名字");
      scanf("%s",infile);
      printf("请输入要复制文件的名字:");
      scanf("%s",outfile);
         
      if((in=fopen(infile,"r"))==NULL)
      {
      printf("打开文件infile失败\n");
      exit(0);
      }
            if((out=fopen(outfile,"w"))==NULL)
      {
      printf("打开文件outfile失败\n");
      exit(0);
      }
      ch=fgetc(in);
      while(!feof(in))
      //while(ch!=EOF)
      {
                fputc(ch,out);
                putchar(ch);
                ch=fgetc(in);
               
      }
      putchar(10);
      fclose(in);
      fclose(out);
      return 0;
}

SUIYUNZOU 发表于 2021-2-18 15:12:14

本帖最后由 SUIYUNZOU 于 2021-2-18 15:16 编辑

多谢

SUIYUNZOU 发表于 2021-2-18 15:15:33

这是不是把读的字符又写读的文件中?
页: [1]
查看完整版本: c语言的文件问题,哪位大佬过来瞧瞧哈?