c++ - fscanf C++ 等价物

标签 c++ c

我想将以下 C 代码翻译成 C++。

FILE *fp = NULL;
fp = fopen("./filename", "r");
int i = 0;
fscanf(fp, "%d\n", &i);
uint16_t j = (uint16_t) i;

这是我想出的:

  ifstream file;
  string filename = "./filename";

  file.open(filename.c_str(), ios::in);
  errno = 0;
  if (file.fail()) {
      int tmp = errno;
      std::cout << file.c_str () << " not found: strerror(" << tmp << "): " << strerror(tmp) );
  }
  int i = 0;
  file >> i >> std::endl;       
  uint16_t j = (uint16_t) i;

我想知道语法是否正确或是否可以改进,更重要的是它是否对所有类型的输入都是安全的。

最佳答案

int read_int(const std::string file_name) {
    std::ifstream file(file_name); //the file will close itself on destruction
    std::uint16_t i;
    //extract type, don't worry about what it is it will either compile or not
    if(!(file >> i)) { //Catch failure
         //or however you wish to deal with it.
         throw std::runtime_error("can't read file");
    }
    return i;
}

int main() {
    try{
        std::uint16_t i=read_int("./filepath");
        //do with i...
    }
    catch(const std::exception& e) {
         std::cerr << e.what() << std::endl;
         return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

请注意,如果您没有 C++11,那么您将需要使用 c_str() 打开文件,但首选字符串方法。

编辑:fstream 自己关闭,没有必要自己关闭它,功能就在那里,以防你必须这样做,但是依赖 RAII 语义要好得多:

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

RAII 规定您应该在构造时打开文件,它会在销毁时关闭,这确保没有任何无效的(不包括 EOF,文件未找到...)fstream 对象防止错误。 RAII 是 C++ 中的基本结构,应该在涉及资源的地方使用。

fstream 析构函数的文档在这里:

http://en.cppreference.com/w/cpp/io/basic_fstream

destructs the basic_fstream and the associated buffer, closes the file

关于c++ - fscanf C++ 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10283408/

相关文章:

c++ - 在 C++ 应用程序中动态使用 libmysql.dll

c - 在 C 中分配结构的指针实例

c - 标记化缓冲区段错误

c - 将可变长度参数传递给函数而不检查它的长度?

c++ - 从 C 调用 C++ 方法

c++ - 具有不同模板参数的相同类不能访问彼此的私有(private)字段

c++ - Arduino双命令

c++ - size_t ptrdiff_t 和地址空间

c++ - 运算符重载内部调用转换

c - 指针式类型转换