【问题标题】:I have some problems with fopen() for c-string我对 c-string 的 fopen() 有一些问题
【发布时间】:2021-06-02 08:14:50
【问题描述】:

我有一个存储为 c 字符串的文件名。我需要打开文件并计算其中的行数。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main() {
  char str[] = "myfile.txt";
  FILE* file = fopen(str, "r");
  int counter = 0, ch = 0;
  while (EOF != (ch = fgetc(file)))
    if (ch == '\n')
      ++counter;
  fclose(file);
  printf("%d", counter);
  return 0;
}

如果我使用fopen("myfile.txt", "r") insted,evrething 就可以正常工作。如何使其与 c 字符串文件名一起使用。

【问题讨论】:

  • 什么是“c-string”?你的意思是std::string?或者你看到了什么错误?另外,你的代码不是c,所以我删除了那个标签。
  • 错字? fopen("myfile", "r")"myfile.txt";
  • @KenY-N C 字符串(或 C 样式字符串)对于 C++ 开发人员意味着以空结尾的 char[]char*。它们被这样称呼以区别于std::string。 C 风格的数组也一样。
  • 这段代码运行良好(除了微妙的“最后一个换行符”问题)。您可能正在犯一些其他微不足道的错误,例如 @RichardCritten 提到的。

标签: c++ file file-io stream c-strings


【解决方案1】:

use string.c_str()

int main() {
  string path = "myfile.txt";
  FILE* file = fopen(path.c_str(), "r");
  int counter = 0, ch = 0;
  while (EOF != (ch = fgetc(file)))
    if (ch == '\n')
      ++counter;
  fclose(file);
  printf("%d", counter);
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2016-04-06
    相关资源
    最近更新 更多