'Creating a file using fopen()
I am just creating a basic file handling program. the code is this:
#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
printf("Error",);
}
fclose(p);
}
This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success. I am using Windows 7 and compiler is Dev C++ version 5
Solution 1:[1]
Change the mode argument in fopen(const char *filename, const char *mode)
from:
p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0) // ^
To this:
p=fopen("D:\\TENLINES.TXT","w");//this will create a file for writing.
if(p==NULL) // ^ //If the file already exists, it will write over
//existing data.
If you want to add content to an existing file, you can use "a+" for the open mode.
See fopen() (for more open modes, and additional information about the fopen family of functions)
Solution 2:[2]
According to tutorial, fopen
returns NULL when error occurs. Therefore, you should check if p
equals NULL
.
Also, in printf("Error",);
, omit the comma after string.
Solution 3:[3]
Yes you should open the file in write mode. Which creates the file . Read mode is only to read content or else you can use "r+" for both read and write.
Solution 4:[4]
You should be able to open the file, but you need to make it first. Make a txt document with the name res.txt. It should be able to write your result into the text document.
<?php
$result = $variable1 . $variable2 "=" .$res ."";
echo $result;
$myfile = fopen("res.txt", "a+") or die("nope");
fwrite($myfile, $result);
fclose($myfile)
?>
Solution 5:[5]
fopen() Syntax:
FILE *fp;
fp=fopen(“data.txt”,”r”);
if(fp!=NULL){
//file operations
}
It is necessary to write FILE in the uppercase. The function fopen() will open a file “data.txt” in read mode. The fopen() performs the following important task.
It searches the disk for opening the file.
In case the file exists, it loads the file from the disk into memory. If the file is found with huge contents then it loads the file part by part.
If the file does not exist this function returns a NULL. NULL is a macro defined character in the header file “stdio.h”. This indicates that it is unable to open file. There may be following reasons for failure of fopen() functions. a.When the file is in protected or hidden mode. b.The file may be used by another program.
It locates a character pointer, which points the first cha racter of the file. Whenever a file is opened the character pointer points to the first character of the file
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Tlacenka |
Solution 3 | Chetan |
Solution 4 | throwaway1992 |
Solution 5 | Mahendra suthar |