c - 使用标准库写入文件

标签 c fopen fwrite fread printf

我从来没有在将数据写入文件时遇到过这么多麻烦!我从 MinGW 运行 GCC,因为我习惯在 Linux 中使用 GCC。我通常使用 Linux 系统调用 open()、write() 和 read(),但我现在正在编写一个 Windows 程序,我在 Windows 中使用 read()/write() 遇到了麻烦,所以我只是使用标准库。无论如何,我遇到的问题是我不知道如何写入文件!我已经定义了“FILE *”变量,使用了 fopen()、“r+b”、“wb”和“w+b”,但我仍然无法使用 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) {

这是您在代码中第二次将 fopen 的结果分配给 infile。你可能想要 outfile 在那里。

关于c - 使用标准库写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10263531/

相关文章:

c - 谁检测拼写错误的函数名称?编译器还是链接器?

C fopen() 和 fgets() 问题

c - 在C中发送图像文件

c - 写入文件时是否需要调用 fclose()

无法通过 C 中的 fwrite 和 fread 复制文本文件

PHP fwrite 总是返回要写入的字节数,即使文件不存在也是如此,这是预期的行为吗?

c - Makefile:通配符和 patsubst 不会更改文件源名称

比较两个字符串 - 获取较长字符串的正确部分

c - 指针数组中出现警告 "initialization from incompatible pointer type"

C:打开的文件太多