使用标准库写入文件

问题描述:

我从来没有将数据写入文件这么麻烦!我从MinGW运行GCC,因为我习惯在Linux中使用GCC。我通常使用Linux系统调用open(),write()和read(),但现在我正在编写Windows程序,并且在Windows中使用read()/ write()时遇到问题,所以我只是使用标准库。无论如何,我遇到的问题是我不知道如何写入文件!我用“r + b”,“wb”和“w + b”定义了“FILE *”变量,用fopen(),但我仍然无法用fwrite()或fprintf()写入输出文件。我不知道我什么都做错了!下面是我的源:使用标准库写入文件

#include <limits.h> 
#include <math.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <strings.h> 

#define DEBUG 1 

/*** Global functions ***/ 
double highfreq(double deg); 

/*** Global variables ***/ 
double sin_now; 

unsigned int *ptr; 
unsigned char *key, *infilename, *outfilename; 
FILE *infile, *outfile, *keyfile; 

const char *pipe_name="[pipe]"; 

int main(int argc, char *argv[]) { 
    unsigned int x, y, z; 

    if(argc!=3) { 
     fprintf(stderr, "Syntax error: %s <infile.txt> <outfile.wav>", argv[0]); 
     return 1; 
    } 
    if(argv[1][0]=='-') { 
     infile=stdin; 
     infilename=(unsigned char *)pipe_name; 
    } 
    else { 
     infilename=argv[1]; 
     if((infile=fopen(infilename, "rb"))==NULL) { 
      fprintf(stderr, "Could not open input file for modulation.\n", infile); 
      return 2; 
     } 
    } 
    if(argv[2][0]=='-') { 
     outfile=stdout; 
     outfilename=(unsigned char *)pipe_name; 
    } 
    else { 
     outfilename=argv[2]; 
     if((infile=fopen(outfilename, "wb"))==NULL) { 
      fprintf(stderr, "Could not open/create output file for modulation.\n", outfile); 
      return 3; 
     } 
    } 
    if(DEBUG) printf("Input file:\t%s\nOutput file:\t%s\n", infilename, outfilename); 

    fprintf(outfile, "Why won't this work!?\n"); 

    fclose(infile); 
    fclose(outfile); 
    return 0; 
} 

double highfreq(double deg) { 
    double conv, rad; 

    conv=M_PI/180; 
    rad=deg*conv; 
    return sin(rad); 
} 

我终于要做一个WAV文件作为输出,因而有“highfreq()”功能,但现在我甚至无法得到它写入一个文件!如果有帮助的话,fprintf()返回错误值-1。我不是很明白,但是因为从我读到的内容来看,这只是表示出现了错误,但没有更多。

outfilename=argv[2]; 
    if((infile=fopen(outfilename, "wb"))==NULL) { 

这是第二次在代码分配的fopeninfile结果。那里你可能想要outfile

+0

啊!最有可能的罪魁祸首!我(显然)复制粘贴这两个部分,并且改变(几乎:P)所有的变量!当我到达我的电脑时,我会尝试它! – Sean 2012-04-22 14:21:06

+0

我对(重大)延误表示歉意;我碰巧正在经历我的问题,看到我从未回答过这个问题!是的,彻底的阅读证明是必要的。谢谢,这是答案。 – Sean 2015-02-15 18:05:04