草庐IT

c++ - 需要帮助将 c 转换为 c++(简单错误但无法修复)

coder 2023-11-17 原文

我有一个 C++ 作业。作业要求将一个c程序转换成c++。 下面是问题:

You are requested to convert the following C function into a C++ function and then embed it into a complete program and test it. Note that this function copies a binary file of integers and not a text file. The program must accept the arguments (the file to copy and the file to be copied to) from the command line.

/* ==================== cpyFile =====================

This function copies the contents of a binary file
of integers to a second file.
Pre fp1 is file pointer to open read file
fp2 is file pointer to open write file
Post file copied
Return 1 is successful or zero if error
*/
int cpyFile (FILE *fp1, FILE *fp2)
{
  /* Local Definitions */
  int data;

  /* Statements */
  fseek (fp1, 0, SEEK_END);
  if (!ftell (fp1))
  {
    printf ("\n\acpyFile Error : file empty\n\n");
    return 0;
  } /* if open error */
  if (fseek (fp1, 0, SEEK_SET))
    return 0;
  if (fseek (fp2, 0, SEEK_SET))
    return 0;

  while (fread (&data, sizeof (int), 1, fp1))
    fwrite (&data, sizeof (int), 1, fp2);
  return 1;
} /* cpyFile */

我尽了最大的努力并设法转换了它,但不幸的是,当我使用它时,复制后得到的文件是空的。以下是我的回答:

#include <fstream>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
  if(argc!=3)
  {cerr<<"invalid number of arguments. must be 3."<<endl;exit(1);}

  fstream fp1(argv[1],ios::in);
  if(!fp1)+{cerr<<argv[1]<<" could not be opened"<<endl;exit(1);}

  fstream fp2(argv[2],ios::out);
  if(!fp2)+{cerr<<"file could not be found."<<endl;exit(1);}


  int data;

  fp1.seekg (0,ios::end);
  if (!fp1.tellg ())
  {
    cout<<"\n\acpyFile Error : file empty\n\n";
    return 0;
  } /* if open error */
  if (fp1.seekg (0, ios::beg))
    return 0;
  if (fp2.seekg (0, ios::beg))
    return 0;

  while (fp1.read (reinterpret_cast<char*>(&data), sizeof (int)))
  {
    fp2.seekp(0);
    fp2.write (reinterpret_cast<char*>(&data), sizeof (int));
  }
  return 1;
}

我已尽力而为,一切正常,除了当我复制一个二进制文件时,我得到的文件是空的,我不知道为什么。

最佳答案

正如其他人所说,您需要以二进制模式打开文件

fstream fp1(argv[1], ios::in | ios::binary); // combine ios::in with ios::binary

fstream fp2(argv[2], ios::out | ios::binary); // combine ios::out with ios::binary

或者你可以让它们ifstream(in file stream只读)和ofstream(out file stream,仅用于写入)并删除 ios::inios::out 因为 ifstream 隐含了 ios::inofstream 意味着 ios::out:

ifstream fp1(argv[1], ios::binary);

ofstream fp2(argv[2], ios::binary);

你需要这样做,因为如果你不这样做,当你从 \r\n 中读取或写入文件时,文件将被翻译\r\n 等,这会弄乱您的二进制数据,而这些二进制数据可能恰好包含这些字节。

这个:

if (fp1.seekg (0, ios::beg))
    return 0;

if (fp2.seekg (0, ios::beg))
    return 0;

将始终使您的代码返回,因为 seekg 返回您调用它的对象。在这方面,它不等同于 fseek,因为 fseek 在成功时返回 0。所以你永远不会进入 while 循环。将那些从 if 语句中取出,使其看起来像这样:

fp1.seekg(0, ios::beg);
fp2.seekg(0, ios::beg);

或者如果你必须进行检查,你想做

if (!fp1.seekg (0, ios::beg)) // notice the added !
    return 0;

if (!fp2.seekg (0, ios::beg)) // notice the added !
    return 0;

此外,这个(在 while 内):

fp2.seekp(0);

将要写入的点设置为文件的开头。所以除了在文件的开头,你永远不会写任何东西。只需完全删除该行即可。

此外,您在循环内有一个 return,这使得它在第一次迭代时返回。将 return 1; 移到循环之外,这样您只能在循环完成后返回。 没关系,由于不寻常的大括号样式而导致误读。

关于c++ - 需要帮助将 c 转换为 c++(简单错误但无法修复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828235/

有关c++ - 需要帮助将 c 转换为 c++(简单错误但无法修复)的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  5. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  6. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  7. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  8. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  9. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  10. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

随机推荐