简体   繁体   English

C - fwrite()没有输出到文件

[英]C - fwrite() not outputting to file

Never used fwrite(), so I'm not sure exactly what I'm doing wrong. 从未使用过fwrite(),所以我不确定我到底做错了什么。 I'm just testing it now and all I want to do is try to write a single char out to a file until it reaches the end. 我现在只是测试它,我想要做的就是尝试将一个char写入文件,直到它到达终点。 The file I'm writing to is one I downloaded from my teacher's website. 我写的文件是我从老师的网站上下载的文件。 When I check the properties of it, the type is only listed as "file". 当我检查它的属性时,类型仅列为“文件”。 It's supposed to just be an empty 2MB file for us to write our code to (file system lab if anyone's wondering). 它应该只是一个空的2MB文件,我们可以编写我们的代码(文件系统实验室,如果有人想知道)。 Here's my code: 这是我的代码:

#include <stdio.h>
#include <string.h>
int main()
{
    char c;
    FILE *fp;   
    char testing[2] = {'c'};  

    fp = fopen("Drive2MB", "rw"); 

    fseek(fp, 0, SEEK_SET);     //make sure pointers at beginning of file
    while((c=fgetc(fp))!=EOF)
    {
        fwrite(testing, 1, sizeof(testing), fp);
        fseek(fp, 1, SEEK_CUR);  //increment pointer 1 byte
    }
    fclose(fp);
} 

When I run this, an error message pops up saying "Debug Assertion Failed!...Expression:("Invalid file open mode",0) and prints "The program '[3896] filesystem.exe: Native' has exited with code 3 (0x3)." 当我运行它时,会弹出一条错误消息,说“Debug Assertion Failed!... Expression :(”无效的文件打开模式“,0)并打印”程序'[3896] filesystem.exe:Native'已退出代码3(0x3)。“

You have opened the file for reading (that's what the r stands for in fopen("Drive2MB", "r"); ). 你打开了文件进行阅读(这就是r代表fopen("Drive2MB", "r"); )。 You may not write to a file opened for reading. 您可能无法写入为阅读而打开的文件。

You're opening it in read only mode 你是以只读模式打开它

Use r+ for the fopen 使用r +表示fopen

fp = fopen("Drive2MB", "r")

your openning your file in read only 以只读方式打开文件

try 尝试

fp = fopen("Drive2MB", "r+"); 

You've opened the file for reading with the "r" part of fopen. 你用fopen的“r”部分打开了文件进行阅读。 To write to the file, you can open it in read/write mode or write mode. 要写入文件,可以在读/写模式或写模式下打开它。

// Read/write mode
fp = fopen("Drive2MB", "r+");

// Write only mode
fp = fopen("Drive2MB", "w");

I never like to use "rw" personally. 我从不喜欢亲自使用“rw”。 When you open a file, it really should have one reason to be opened. 当你打开一个文件时,它应该有一个理由被打开。 You also do not need to call fseek to move to the start of the file and you do not need to use fseek to advance the file pointer. 您也不需要调用fseek来移动到文件的开头,也不需要使用fseek来推进文件指针。 fopen will automatically open it to the start of the file and fwrite will automatically advance the pointer. fopen会自动将其打开到文件的开头,fwrite会自动推进指针。 fseek should only be used if you are "seek"ing inside of the file to get to a specific point. 只有在“寻找”文件内部才能到达特定点时才应使用fseek。

In the case you've given, you would only need write ("w") mode since you are not ever reading from the file. 在你给出的情况下,你只需要写(“w”)模式,因为你没有从文件中读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM