【问题标题】:How to transfer contents from one file to another in Ubuntu.? [duplicate]如何在 Ubuntu 中将内容从一个文件传输到另一个文件。? [复制]
【发布时间】:2019-11-06 06:28:20
【问题描述】:

我正在尝试将一个文件的内容复制到 linux 中的另一个文件。 我认为我的逻辑是正确的,但我不明白错误是什么。

我的函数有 3 个参数。第三个参数是一个字符串,它是应该从中读取内容的文件名。

#include<iostream>
#include <curses.h>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
void process(int cvar, int cclause, string fnm)
{
    ifstream fs;
    ofstream ft;

    fs.open("contents.txt");
    if(!fs)
    {
        cout<<"Error in opening source file..!!";
    }
    ft.open(fnm,ios::app);
    if(!ft)
    {
        cout<<"Error in opening target file..!!";
        fs.close();
    }

char str[255];
while(fs.getline(str,255))
{
    ft<<str;
}



    cout<<"File copied successfully..!!";
    fs.close();
    ft.close();
    getch();
}

这是我得到的错误:

g++ mainProj.cpp -lz3
/tmp/ccLBpiRs.o: In function `process(int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
mainProj.cpp:(.text+0x172): undefined reference to `stdscr'
mainProj.cpp:(.text+0x17a): undefined reference to `wgetch'
collect2: error: ld returned 1 exit status

【问题讨论】:

  • 顺便说一句,你说你认为你的逻辑是正确的,但你也说第三个参数是要读取的文件名(据说),而你的代码显然是附加到它的。跨度>
  • 顺便说一句,复制文件的一种更快、更有效的方法是以二进制模式打开它们并使用istream::readostream::writeuint8_t 数组。复制文件的最佳技术是让操作系统为您复制文件。
  • 你有使用 istream::read 和 ostream::write 的示例程序吗?

标签: c++ file


【解决方案1】:

#include &lt;ncurses.h&gt; 并与 -lncurses 链接。

更多here.

【讨论】:

    【解决方案2】:

    如何在 Ubuntu 中将内容从一个文件传输到另一个文件?

    您可以使用输入流来读取文件,使用输出流来写入文件。

    mainProj.cpp:(.text+0x172): undefined reference to `stdscr'
    mainProj.cpp:(.text+0x17a): undefined reference to `wgetch'
    

    您已经包含了一个标头 &lt;curses.h&gt; 并使用了在那里声明的函数,但是您未能链接到定义这些函数的库。

    【讨论】:

      【解决方案3】:

      如何在 Ubuntu 中将内容从一个文件传输到另一个文件。?

      这是一个简单高效的 sn-p。还有更有效的方法:

      #include <iostream>  
      #include <fstream>
      #include <string>  
      
      void copy_file(const std::string&  source_filename, const std::string& destination_filename)
      {
          std::ifstream input(source_filename.c_str(), "b");
          std::ofstream output(destination_filename.c_str(), "b");
          const size_t BUFFER_SIZE = 1024 * 16;
          static uint8_t buffer[BUFFER_SIZE];
          while (input.read(buffer, BUFFER_SIZE))
          {
              const size_t bytes_read = input.gcount();
              output.write(buffer, bytes_read);
          }
      }
      

      上面的代码使用了一个很大的缓冲区。文件内容被读取(使用二进制模式)到缓冲区,然后使用块 I/O 写入另一个文件。文件是流设备,在传输 {large} 块数据时效率最高。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-04
        • 1970-01-01
        相关资源
        最近更新 更多