如何打开一个文本文件,这不是在同一文件夹? [英] How to open a text file that's not in the same folder?

查看:130
本文介绍了如何打开一个文本文件,这不是在同一文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于C这不是我习惯用编程语言,我不知道如何做到这一点。

Since C it's not a language I am used to program with, I don't know how to do this.

我在那里我有所有的.c和.h文件和conf文件夹下有一个文件的config.txt读取一个项目文件夹。我怎样才能打开?

I have a project folder where I have all the .c and .h files and a conf folder under which there is a config.txt file to read. How can I open that?

FILE* fp = fopen("/conf/config.txt", "r");

if (fp != NULL)
{
    //do stuff
}

else
   printf("couldn't open file\n");

我不断收到错误消息。为什么呢?

I keep getting the error message. Why?

顺便说一句,这只能在Windows上运行,而不是Linux。

Btw, this only have to work on windows, not linux.

感谢。

推荐答案

最简单的方式是使用绝对路径...

The easy way is to use an absolute path...

my_file = fopen("/path/to/my/file.txt", "r");

或者你也可以使用相对路径。如果你的可执行文件在 /家/我的/ bin中和你的txt文件是在 /家庭/ ME / DOC ,那么你的相对路径可能类似于

Or you can use a relative path. If your executable is in /home/me/bin and your txt file is in /home/me/doc, then your relative path might be something like

my_file = fopen("../doc/my_file.txt", "r");

在相对路径要记住的重要一点是,它是相对的当前工作目录的运行可执行文件时。所以,如果你使用上面的相对路径,但你在你的 / tmp目录目录,你跑了 /家庭/ ME /斌/ MYPROG ,它会尝试打开 / tmp目录/../ DOC / my_file.txt适用(或 /doc/my_file.txt ),这很可能就不存在了。

The important thing to remember in relative paths is that it is relative to the current working directory when the executable is run. So if you used the above relative path, but you were in your /tmp directory and you ran /home/me/bin/myprog, it would try to open /tmp/../doc/my_file.txt (or /doc/my_file.txt) which would probably not exist.

更强大的选择是把文件路径作为参数传递给该程序,并传递作为第一个参数的fopen 。最简单的例子是只使用的argv [1] 主要的参数,即

The more robust option would be to take the path to the file as an argument to the program, and pass that as the first argument to fopen. The simplest example would be to just use argv[1] from main's parameters, i.e.

int main(int argc, char **argv)
{
    FILE *my_file = fopen(argv[1], "r");
    /* ... */
    return 0;
}

当然,你会希望把错误检查,以验证 ARGC > 2,等等。

这篇关于如何打开一个文本文件,这不是在同一文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆