2010-11-15 90 views

回答

19
#include <stdio.h> 

void adx_store_data(const char *filepath, const char *data) 
{ 
    FILE *fp = fopen(filepath, "ab"); 
    if (fp != NULL) 
    { 
     fputs(data, fp); 
     fclose(fp); 
    } 
} 
1

像这样的东西应该这样做:

#include <stdio.h> 
: : : 
int adxStoreData (char *filepath, char *data) { 
    int rc = 0; 

    FILE *fOut = fopen (filepath, "ab+"); 
    if (fOut != NULL) { 
     if (fputs (data, fOut) != EOF) { 
      rc = 1; 
     } 
     fclose (fOut); // or for the paranoid: if (fclose (fOut) == EOF) rc = 0; 
    } 

    return rc; 
} 

它会检查各种错误条件,如文件I/O问题,并返回1(真),如果没事,0(假),否则。这可能是应该正在做的事情,即使在PHP中也是如此。

+2

fclose(fOut)!= EOF怎么样? ;-) – 2010-11-15 09:34:52

+1

也许应该也有一些文件路径和数据断言,以确保既不是NULL? ;-) – 2010-11-15 09:53:31

+2

检查'fclose()'是否成功不仅仅是偏执狂。输出通常是缓冲的;在'fclose()'调用之前很可能没有任何内容会写入文件。 – 2011-08-31 02:37:55