如何在特定路径中获取已知文件的文件指针(FILE *)?

时间:2013-08-26 08:40:17

标签: c linux file unix

读取/写入一个文件我需要在Unix环境下用C语言编写文件指针。 我知道文件名和路径,但如何使用其名称和路径获取文件指针。

4 个答案:

答案 0 :(得分:3)

#include <stdio.h>
FILE * pFile;
pFile = fopen ("myfile.txt","w");

答案 1 :(得分:1)

像这样导入标准输入/输出标题

#include <stdio.h>

然后为要打开的文件创建一个指针。

FILE * file_pointer;
file_pointer = fopen ("[path to file]","w");
fclose(file_pointer);

注意:如果文件与源文件不在同一目录中,请指定文件的完整路径。 完成所需的操作后,别忘了关闭文件

答案 2 :(得分:0)

根据ssmithstone的帖子:

#include <stdio.h>
FILE * pFile;
/* open file and check if was successful */ 
if ((pFile = fopen("myfile.txt", "w")) == NULL)
{
/* couldn't open file; do some error handling if u want */
}
else
{
/* do s.th. */
/* close file */
fclose(pFile);
}

在这种情况下,w意味着写作。如需其他选项,请查看Yu Hao发布的链接。

答案 3 :(得分:0)

好像你是C编程的新手,我已经为你编写了一个C程序,你可以对它进行分析,我相信这对你肯定有帮助。

#define size 50
#include <stdio.h> 
int main() 
{ 
    char name[size]; 
    FILE *file;
    file = fopen("your_file.txt","w");
    printf("Please enter your first name\n");
    scanf("%s",name);
    fprintf(file,"%s",name);
    fclose(file); 
    return 0; 
}

<强>详细信息:

  • 在第7行中,第二个参数 w 用作文件打开模式 - 具有写权限。
  • 文件指针用于创建/打开名为“ your_file.txt ”的文件。
  • function fprintf()printf()函数相同,但它不会在控制台上写入,而是写入您的文件。
  • 最后我们需要关闭文件写入操作,因此我们使用fclose()函数

<强>更新

要指定路径,可以使用filename.fileextension编写文件路径 例如:您可以将其写为

file = fopen("/home/depthgr8/Desktop/your_file.txt","w"); 

如果路径存在,这将在给定路径中创建your_file.txt,否则会引发运行时异常 - 分段错误(核心转储)