Won't create txt file C program - c

This is my code
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("file.txt","a+");
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
Don't understand why it won't create a txt file
help

Please try perror to check if you have permission to write to the file or not. That is the problem most of the time. Add this after fopen
if (!file)
perror("fopen");

You need to check for errors in your program. fopen() can fail for a variety of reasons. We can either inspect errno, or use perror / strerror to print a useful message.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = fopen("file.txt","a+");
if (file == NULL) {
perror("Failed to open the file");
exit(-1);
}
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
For example, if a file exists in the current directory, but is owned by a different user:
[8:40am][wlynch#watermelon /tmp] ./foo
Failed to open the file: Permission denied

Create a file if one doesn't exist - C
here are answers...The one that's under the marked one worked for me on my s.o. The way you are trying to do doesn't work on windows, but works on linux. Sorry for saying what I said before...Both operating systems have their bright and not so bright side.

Related

How to read a configuration file, or create one if it's missing

How do you make a file, but only if it doesn't already exist? Like.. I want to read a text file, but if it doesn't exist, I want to create one with some default text.
I can create the file with the default text easy enough. And I can append or overwrite it if it already exists.
But if it already contains some text, I want to READ FROM it. Not WRITE TO it. Like you might do with a dot file or configuration file, to set a default configuration in the event the file is missing.
This is quite simple with Python, but I'm trying to make the transition to C, and It's more challenging than I'd anticipated.
So my function basically looks something like this so far. The text is just a placeholder for whatever the real text might be.
main() {
FILE *fp;
fp = fopen("./filename.txt", "w");
fprintf(fp, "some default text\n");
fclose(fp);
}
So just to clarify: If ./file.txt already exists, it shouldn't be written to. It should be read from.
When I say "read from", it could be printed to stdout, or stored in an array for instance, but that's probably beyond the scope of the question.
Considering your example there are two main mistakes:
You don't check the result of fopen thus you don't know whether your file has been successfully opened (here is the key to the answer).
printf function prints directrly to stdout and you have to use fprintf one for printing to your configuration file.
I propose the following: try to fopen your configuration file (e.g. ./filename.txt) for r and check the result of this call. Upon successful completion fopen return a FILE pointer to your existing configuration file. If the file doesn't exist fopen returns NULL and errno is set to ENOENT. In this case you can create a new configuration file and write a default config into it.
Please see man 3 section for the corresponding docs.
UPD:
Here is PoC for the proposal
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE *fp = fopen(".rc", "r");
if (!fp)
switch (errno) {
case ENOENT:
fprintf(stderr, "No config found, creating the default one\n");
fp = fopen(".rc", "w");
if (!fp) {
perror("Failed to create default config: ");
return EXIT_FAILURE;
}
/* write default config here */
break;
default:
perror("Failed to open existing config: ");
return EXIT_FAILURE;
}
/* read existing config here */
return EXIT_SUCCESS;
}
Use stat before opening your file. If the stat is successful then the file exists, if it is not, check for ENOENT in errno.
Example
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat file_infos;
char file_path[] = "/whatever"
if (stat(file_path, &file_infos) != 0)
{
if (errno == ENOENT)
{
// Do whatever when the file wasn't found
}
else
{
// Error accessing the file, check the errno for more infos
}
}
else
{
// File exists, do whatever you like with it.
}
}
Enjoy :)

canĀ“t open txt file

#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
Output is Error! opening file
I have program and txt file in same dir.
How can I direct access to that file?
To diagnose, use the system command to issue a ls or dir depending on your platform. That will tell you where you are running from. Odds are it is a different location than the files you are trying to open.
As suggested in the comment, try replacing printf with perror
if ((fptr = fopen("program.txt", "r")) == NULL)
{
perror("Error");
// Program exits if file pointer returns NULL.
exit(1); // Exiting with a non-zero status.
}
perror prototype is
void perror(const char *str)
where str is the C string containing a custom message to be printed before the error message itself.
However some causes of the of the file not being read are
File is not present in the current working directory. If this is the case, rectifying the path should fix the issue.
The program might not have the permissions to read from the file usually because of a setting related to discretionary access control. Perhaps do a chmod with file?
I made a quick run of your program on TURBOC++ by Borland and it executed without complaining any sort of Warning or Error
As mentioned in the earlier posted answers, you should replace printf by perror
CURRENT REPLACE BY
printf("Error! opening file"); perror("Error! Opening File.");
As in your case of file not found printf("Error! opening file"); will result in :
Error! Opening file.
However in case of perror("Error! Opening File."); if the file program.txt does not exist, something similar to this may be expected as program output
The following error occurred: No such file or directory
The difference is obvious from above explanations.
Regarding your program, I am making an assumption that either your path to the file is wrong or there is some problem with your compiler.
Try to open your file in w+ mode also to ensure that the file exist.

fopen returning NULL when trying to open a bmp file (C++)?

FILE * in;
in = fopen("file1.bmp", "rb");
if (in == NULL) {
perror("file1.bmp");
return ;
}
Why is it that I am not able to open the *.bmp file. fopen() is returning NULL.
Can anyone kindly help me how to successfully open a BMP file. Should I use some other C++ function. If yes, plz let me know. An example would be very helpful. I am using VC++ in VS2008.
Thanks in advance.
The file does not exist, or you can't read from it (maybe file permissions)?
You might have a working directory issue. Try opening the file with a fully qualified path.
Also this is a plain C question
#include<stdio.h>
#include <errno.h>
int main()
{
FILE * in;
in = fopen("file1.bmp", "rb");
if (in == NULL) {
perror("file1.bmp");
printf("Error %d \n", errno);
return ;
}
}
using this way see errno and find its meaning from here http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

SImple C Program opening a file

I'm trying to make a program to open a file, called "write.txt".
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("write.txt", "w");
return 0;
}
Should this work? Because it returns nothing.
Other than an old variant of main, there's not really much wrong with that code. It should, barring errors, create the file.
However, since you're not checking the return value from fopen, you may get an error of some sort and not know about it.
I'd start with:
#include <stdio.h>
#include <errno.h>
int main (void) {
FILE *fp;
fp = fopen ("write.txt","w");
if (fp == NULL) {
printf ("File not created okay, errno = %d\n", errno);
return 1;
}
//fprintf (fp, "Hello, there.\n"); // if you want something in the file.
fclose (fp);
printf ("File created okay\n");
return 0;
}
If you're adamant that the file isn't being created but the above code says it is, then you may be a victim of the dreaded "IDE is working in a different directory from what you think" syndrome :-)
Some IDEs (such as Visual Studio) will actually run your code while they're in a directory like <solution-name>\bin or <solution-name>\debug. You can find out by putting:
system ("cd"); // for Windows
system ("pwd") // for UNIXy systems
in to your code to see where it's running. That's where a file will be created if you specify a relative path line "write.txt". Otherwise, you can specify an absolute path to ensure it tries to create it at a specific point in the file system.
What did you expect it to 'return' - it opens a file, on most platforms creating one if it doesn't exist.
You should probably fclose(fp) the file at the end.
I think you want to print the contents of file write.txt. (Assume it contains characters).
#include <stdio.h>
int main()
{
FILE *fp,char ch;
fp=fopen("write.txt","r");
if(fp==NULL)
{
printf("Some problem in opening the file");
exit(0);
}
else
{
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
}
fclose(fp);
return 0;
}
I think you should study some more fundamentals in C before you start attempting to work with files. A return means some data is passed back to the calling code from the called function.In this case you return 0 at the end of your program. You did not do anything with your FILE pointer except cause a new file to be created...

How can I clear the contents of a file

I would like to know how the contents of a file can be cleared in C. I know it can be done using truncate, but I can't find any source clearly describing how.
The other answers explain how to use truncate correctly... but if you found yourself on a non-POSIX system that doesn't have unistd.h, then the easiest thing to do is just open the file for writing and immediately close it:
#include <stdio.h>
int main()
{
FILE *file = fopen("asdf.txt", "w");
if (!file)
{
perror("Could not open file");
}
fclose(file);
return 0;
}
Opening a file with "w" (for write mode) "empties" the file so you can start overwriting it; immediately closing it then results in a 0-length file.
The truncate() call in UNIX is simply:
truncate("/some/path/file", 0);
While you can just open and close the file, the truncate call is designed specifically for this use case:
#include <unistd.h> //for truncate
#include <stdio.h> //for perror
int main()
{
if (truncate("/home/fmark/file.txt", 0) == -1){
perror("Could not truncate")
}
return 0;
}
If you already have the file open, you can use that handle with ftruncate:
#include <stdio.h> //for fopen, perror
#include <unistd.h> //for ftruncate
int main()
{
FILE *file = fopen("asdf.txt", "r+");
if (file == NULL) {
perror("could not open file");
}
//do something with the contents of file
if (ftruncate(file, 0) == -1){
perror("Could not truncate")
}
fclose(file);
return 0;
}
truncate(2) is not a portable call. It only conforms to 4.2BSD. While it is found on most *nix type systems, I would say use a POSIX.1 compliant routines which are pretty much guaranteed on most modern environments (including Windows).
so here is a POSIX.1-2000 compliant code snippet:
int truncate_file(const char *name) {
int fd;
fd = open (name, O_TRUNC|O_WRONLY);
if ( fd >= 0 )
close(fd); /* open can return 0 as a valid descriptor */
return fd;
}
For deleting the contents of a fie obviously there is basic method of opening a file in write mode "w" and then close it without doing any changes in it.
FILE *fp = fopen (file_path, "w");
fclose(fp);
this will delete all the data in file as when you open a already existing file using "w" mode the file is deleted and a new file with the same name is opened for writing, this will result into deletion of contents of your file.
BUT there is truncate syscall in UNIX systems, which is specially for the same purpose and pretty easy to use:
truncate (filepath, 0);
if you have already opened your file so either you close your file before doing truncate or use ftruncate
ftruncate (file_path, 0);

Resources