2016-04-25 41 views
0

我试着去学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); 
} 

我错过什么?

+1

你有写入权限“/ tmp”吗? – jdarthenay

+0

尝试写入其他文件夹。 (这可能是后台程序删除使用的文件的工作。) – BLUEPIXY

+1

检查'fopen()'的结果。如果它不能创建文件,它会返回NULL。 – jdarthenay

回答

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

仍然没有改变任何东西 – Ash

+1

@Ash:你可以把这个文件放到程序目录中来开始。将'/ tmp/test.txt'改为'test.txt' – sjsam

+0

不再工作 – Ash

0

它创造了/ tmp目录一个新的文件test.txt和写入使用两种不同功能的两行。尝试在/ tmp文件夹中找到test.txt。

+0

我无法找到它,我试图创建文件夹并删除它,有和没有文件,但它什么都不做 – Ash

+0

该文件夹是'/ tmp'顺便说一下 – sjsam

+0

感谢您指出@sjsam – AJ93

0

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

0
  • 首先,你需要创建一个从那里你执行这个代码,因为的fopen没有创建目录的话,比temp目录之后,你需要检查下面的代码:
#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); 
    } 
} 
  • 还要记住,当你处理文件操作时,你必须检查你的文件是否打开/创建或不是我们ing用法消息。其实这是编程的好兆头。