簡體   English   中英

無法在C中寫入文本文件

[英]cant write text file in c

我正在嘗試學習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);
}

我想念什么嗎?

引入一些錯誤檢查文件流是很好的

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);

它在/ tmp目錄中創建一個新文件test.txt,並使用兩種不同的功能編寫兩行。 嘗試在/ tmp文件夾中找到test.txt。

fopen()不會為您創建目錄。 在運行該程序之前,需要在當前磁盤的根目錄下創建一個tmp文件夾。

  • 首先,您需要從執行此代碼的位置創建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); } } 
  • 還請記住,在處理文件操作時,始終必須檢查文件是否已打開/創建或不使用“用法”消息。 實際上,這是編程的好兆頭。

我知道這有點晚了,但是我發現代碼可以在我的PC上與以下代碼一起使用...

代替“ /tmp/test.txt” ,使其成為“ tmp / test.txt” 是的,只需刪除“ /”即可

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM