问题
I have a simple program which opens a file and write a text into the file. However, the fopen is always returning BadPtr
as seen in debug mode in Microsoft Visual c++, 2010
.
Below is the warning that is displayed in VS C++, 2010
:
mysample\mysample\main.c(6): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
I thought the warning is a problem and used fopen_s
, however this also doesnt solve the problem. Below is my code:
#include <stdio.h>
int main()
{
FILE *fp;
fp=fopen("c:\\hello.txt","w+");
if(fp==NULL)
{
printf("\nfopen() error\n");
return 1;
}
else
{
fprintf(fp,"\nThis is a sample text file\n");
}
fclose(fp);
return 0;
}
In the above code, the flow doesn't enter the if(fp == NULL)
condition, rather it goes to the else part, but the file is not being created.
Please help regarding the same.
回答1:
If you do not have admin privileges
Create file in you compilation directory
fp=fopen("hello.txt","w+");
This will create file in mysample\mysample
You should have admin privileges, to create file in C:\
if you have admin privileges open command Prompt with Run as Administator and then execute your executable by just giving name.
if you use filename fopen.c
,
you will get fopen.exe
simply run fopen
from command prompt, it will create file in C:\
回答2:
Your code works, but if you want create the file in C:\
you need Admin Privileges, try saving the file in the same file directory of your program, or run an Administrator cmd
and execute your *.exe
there.
来源:https://stackoverflow.com/questions/19330987/simple-fopen-and-fprintf-not-working