簡體   English   中英

嘗試寫入文件時 fprintf 不起作用

[英]when trying to write file fprintf does not work

我只是想打開文件並在文件中寫入一些東西,但是當 visual studio 嘗試執行 fprintf 程序崩潰時,這里是我的代碼

#include<stdlib.h>
int main()
{
    FILE* fPointer;
    fPointer = fopen_s(&fPointer,"‪C:\\asd.txt","w");
    fprintf(fPointer, "If ı can read this then ı can create for loop");
    fclose(fPointer);
    return 0;
}

這是錯誤消息: Access violation writing location 0x0000003A.

fopen_s返回值是一個錯誤號,你用你不應該做的覆蓋你的文件指針。

與返回數據類型FILE *fopen相比,function fopen_s返回數據類型errno_t

在您發布的代碼中,您將變量fPointer的地址傳遞給 function fopen_s ,以便它寫入該變量。 這是對的。 但是,之后,您將 function fopen_s (屬於errno_t類型)的返回值顯式分配給變量fPointer ,從而覆蓋之前由 function fopen_s寫入該變量的內容。 不應這樣做,因為數據類型errno_t與數據類型FILE *具有不同的含義。

此外,作為一般規則,您應該始終在使用FILE *之前檢查文件是否已成功打開。

因此,您應該將代碼更改為如下所示:

#include <stdlib.h>

int main()
{
    FILE* fPointer;
    errno_t err;

    err = fopen_s(&fPointer,"‪C:\\asd.txt","w");
    if ( err == 0 )
    {
        fprintf(fPointer, "If ı can read this then ı can create for loop");
        fclose(fPointer);
    }
    else
    {
        fprintf( stderr, "Error opening file!\n" );
    }

    return 0;
}

如果fopen_s未能創建文件指針,則返回錯誤代碼。 您必須在使用文件指針之前檢查錯誤值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM