c - 使用 freopen 写入子目录

标签 c freopen

我正在尝试使用 freopen 写入子目录内的文件:

freopen("output/output-1.txt", "w", stdout);

我尝试将其更改为输出到当前目录并且它有效。当目标输出文件位于子目录中时,它会无错误地终止;但是没有创建任何文件。创建所需的目录并不能解决问题。

void write_to(int subtask, int tc){
    string output = string("testcases/subtask-") + to_string(subtask) + "-tc-" + to_string(tc);
    freopen(output.c_str(), "w", stdout);
}

int main(){
    for(int i = 1; i <= 25; i++){
        write_to(1, i);
        // rest of code to generate and cout test cases
    }
}

有人能解决这个问题吗?

最佳答案

阅读 freopen(3) 的文档。您应该测试并使用其结果:

The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed.

关于其返回值:

Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

所以你至少需要编码(如果在 Linux 或某些 POSIX 系统上)

void write_to(int subtask, int tc){
   string output = 
     string("testcases/subtask-") + to_string(subtask) 
      + "-tc-" + to_string(tc);
   FILE*outf = freopen(output.c_str(), "w", stdout);
   if (!outf) {
     perror(output.c_str());
     char pwdbuf[128];
     memset (pwdbuf, 0, sizeof(pwdbuf));
     getcwd(pwdbuf, sizeof(pwdbuf)-1);
     fprintf(stderr, "failure in %s\n", pwdbuf);
     exit(EXIT_FAILURE);
   }
}

(上面的代码不会解决您的问题,但会在出错时输出有意义的错误消息;也许您没有在适当的当前目录中运行代码)

我还建议使用 fflush(stdout)fflush(NULL) 结束 main 中的 for 循环.

如果在 Linux 或 POSIX 上,您可能会在文件描述符级别工作(因此编写重定向代码),并使用 open(2) & dup(2) (使用 STDOUT_FILENO 作为 dup2 的第二个参数)。

如果 testcases 是您的 $HOME 中的一个目录(即 ~/testcases/ 由您的 shell 扩展),您会想要

string output =
  string (getenv("HOME")) + "/" 
  + string("testcases/subtask-") + to_string(subtask) 
  + "-tc-" + to_string(tc);

关于c - 使用 freopen 写入子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41040598/

相关文章:

c - 如何将 hping3 的输出从子级传递到父级?

c - 在 linux C 中枚举目录条目时如何忽略子目录

c++ - 在 C++ 中使用 freopen 打开多个文件

linux - 重定向标准输入以完全不提供输入?

如果文件不存在则创建一个文件 - C

c - 如何在 C 中使用 argv 重定向给定文件中的标准输出和标准输入

c - 分段故障Strdup

c - _tzset 和 x 字母时区名称

c - freopen 或 freopen_s,它们到底在做什么?

将二维数组复制到另一个二维数组