【问题标题】:cant write text file in c无法在c中写入文本文件
【发布时间】:2016-04-25 04:56:04
【问题描述】:

我正在努力学习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);
}

我错过了什么吗?

【问题讨论】:

  • 你对“/tmp”有写权限吗?
  • 尝试写入其他文件夹。 (删除使用过的文件可能是后台程序的工作。)
  • 查看fopen()的结果。如果无法创建文件,则返回NULL
  • 我用的是windows,有什么问题吗?
  • @ash 使用 Windows 没有任何问题。但是,/tmp 不是标准的 Windows 目录,而它位于 Linux 中。这就是为什么我要求您显示您的确切运行日志以及您如何检查结果(例如,您运行以验证结果的确切命令)。

标签: c file text


【解决方案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);

【讨论】:

  • 仍然没有改变任何东西
  • @Ash :您可以将文件放在程序目录中开始。将/tmp/test.txt 更改为test.txt
  • 好吧,文件还是空的
  • @Ash :有文件吗?您也有可能正在寻找错误的文件。您是否尝试在代码中将/tmp/test.txt 更改为test.txt。运行代码后。您应该查看代码所在的同一文件夹
  • 我将目录更改为 GitHub 目录,它在那里工作,也许只是权限不允许我在文件上写入。
【解决方案2】:

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

【讨论】:

  • 我找不到它,我尝试创建文件夹并删除它,有和没有文件,但它什么也没做
  • 文件夹是/tmp
【解决方案3】:

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

【讨论】:

    【解决方案4】:
    • 首先,您需要从执行此代码的位置创建 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);
        }
     }
    
    • 还请记住,当您处理文件操作时,您必须始终检查您的文件是否打开/创建或未使用使用消息。其实这是编程的好兆头。

    【讨论】:

      【解决方案5】:

      我知道这有点晚了,但我发现代码可以在我的电脑上使用以下内容...

      "/tmp/test.txt" 改为 "tmp/test.txt"。 是的,只需删除 "/"

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多