不能在c中写文本文件

时间:2016-04-25 04:56:05

标签: c file text

我正在尝试学习c,我正在使用tutorialspoint,他们给我的功能在我的计算机上没有做任何事情,功能是:

#include <stdio.h>

int main (){
    FILE *fp;

    fp = fopen("/tmp/test.txt", "w+");
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);
}

我错过了什么吗?

5 个答案:

答案 0 :(得分:1)

最好用文件流引入一些错误检查

待办事项

fp = fopen("test.txt", "w+"); 
/* 
 * Try creating the file in the same folder for a start
 */

if(fp!=NULL)
{
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
}
else
{

     /* There are multiple reasons you can't open a file like :
      * You  don't have permission to open it
      * A parent directory doesn't exist and so on.
      */

printf("Can't open the file for write\n");
}
fclose(fp);

答案 1 :(得分:0)

它在/ tmp目录中创建一个新文件test.txt,并使用两个不同的函数写入两行。尝试在/ tmp文件夹中找到test.txt。

答案 2 :(得分:0)

fopen()不会为您创建目录。 在运行此程序之前,您需要在当前磁盘的根目录下创建一个tmp文件夹。

答案 3 :(得分:0)

  • 首先,您需要创建执行此代码的temp目录,因为 fopen 没有创建目录,因此需要检查以下代码:
 #include <stdio.h>
 int main ()
 {
   FILE *fp;
   fp = fopen("/tmp/test.txt", "w+");
    if(fp == NULL)
    {   
      printf("Usage Message: File is not open temp/test.txt");
    }
    else
    {
      fprintf(fp, "This is testing for fprintf...\n");
     fputs("This is testing for fputs...\n", fp);
      fclose(fp);
    }
 }
  • 还要记住,当您处理文件操作时,您必须使用Usage消息检查您的文件是否已打开/创建。实际上这是编程的好兆头。

答案 4 :(得分:0)

我知道这有点晚了,但是我发现代码可以在我的PC上使用以下代码...

代替“ / tmp / test.txt” ,将其设置为“ tmp / test.txt” 。 是的,只需删除“ /”