【问题标题】:Enter File Name When Executing Program In C++在 C++ 中执行程序时输入文件名
【发布时间】:2009-07-21 03:12:12
【问题描述】:

我正在学习 C++,然后我正在寻找一些代码来学习我喜欢的领域:文件 I/O,但我想知道我如何调整我的代码以供用户键入他想查看的文件,例如在 wget 中,但我的程序如下:

C:\> FileSize test.txt

我的程序代码在这里:

// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  long begin,end;
  ifstream myfile ("example.txt");
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}

谢谢!

【问题讨论】:

  • 我知道 Stackoverflow 对所有人开放,因此可以免费交换信息,但您会问很多问题,只需简单的 google 搜索即可回答。
  • 我之前在谷歌搜索过!
  • 在这种情况下建议你使用 stat 函数来获取文件大小。如果成功,它会填写“struct stat”,然后您可以 st_size 来检查文件大小的值。上面的代码没有检查文件是否不存在。无论如何,只是很挑剔......重点是打开从命令行传入的文件名:)

标签: c++ file-io


【解决方案1】:

在下面的示例中,argv 包含命令行参数作为空终止的字符串数组,而 argc 包含一个整数,告诉您传递了多少个参数。

#include <iostream>
#include <fstream>
using namespace std;

int main ( int argc, char** argv )
{
  long begin,end;
  if( argc < 2 )
  {
     cout << "No file was passed. Usage: myprog.exe filetotest.txt";
     return 1;
  }

  ifstream myfile ( argv[1] );
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}

【讨论】:

  • 应该是 ifstream myfile ( argv[1] );由于 argv[0] 包含可执行文件的名称。
  • 糟糕应该是 argv[1] 而不是 argv[0]
  • 但是当我键入文件或不键入时,程序的消息是every: size is: 0 bytes。 怎么了?
  • argc 检查错误。 argc==1 没有参数,argc&gt;=2 至少有 1 个参数。
  • 啊,是的,这也应该更新,我会编辑帖子以反映更正。
【解决方案2】:

main() 带参数:

int main(int argc, char** argv) {
    ...
    ifstream myfile (argv[1]);
    ...
}

你也可以变得聪明,为命令行中指定的每个文件循环:

int main(int argc, char** argv) {
    for (int file = 1; file < argc;  file++) {
        ...
        ifstream myfile (argv[file]);
        ...
    }
}

注意 argv[0] 是一个指向你自己程序名的字符串。

【讨论】:

  • 小拼写错误“args[1]”应该是“argv[0]”
【解决方案3】:

Main 接受两个参数,您可以使用它们来执行此操作。看到这个:

Uni ref

MSDN reference (has VC specific commands

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 2015-01-22
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多