Opening a file with a string - c

I'm working on a problem that requires me to adjust the name of a file and then create a new file using the adjusted name. I'm storing the adjusted name in an array called nameHolder[]. I'd like to use nameHolder, which contains "file.txt" as the name of the new file. The code I have is the following:
void createNewFile(char nameHolder[])
{
FILE* myNewFile = fopen(nameHolder, "r");
fprintf("****************%s******************", nameHolder);
fclose(myNewFile);
}
I get NULL for myNewFile and I believe this is due to "file.txt" not existing in the directory, but the problem requires that I create an entirely new file that doesn't already exist.

From the man page:
RETURN VALUE
Upon successful completion fopen(), fdopen(), and freopen()
return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.
For a file to be read, it should exist, which doesn't in your case. fopen returns NULL on failure, you should check for it.
Unrelated:
The prototype of fprintf is:
int fprintf(FILE *restrict stream, const char *restrict format, ...);
The first argument should be a FILE *, remedy it.

You create a file, truncate it present like this:
FILE *myNewFile = fopen(nameHolder, "w");
Otherwise you want the mode "a" (or "a+").

Related

How to read from a text file I made in C

I am new to C, I am just trying to read a simple text file I created in C. I made this file by clicking new -> empty file -> saving it to my desired location and then adding the file extension (.txt) the text file holds a sample sudoku board and the full file name is sudokuchar.txt.
The code I have to read from the file and print it is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpointer = fopen("sudokuchar.txt", "r");
char input[100];
while(fgets(input,100,fpointer))
{
printf("%s",input);
}
fclose(fpointer);
}
so when i compile the program does not print anything and returns -1. I assume something is wrong with the file i am trying to read from?? if some one could help it would be greatly appreciated.
Always check the return values of fopen and other standard library calls. It's most likely that your file doesn't exist. You can make a nice user friendly error message using errno, just make sure to include errno.h. Overall, your code should work, but you NEED to check the return values of things, because fopen returns NULL if it can't find the file.
FILE *fpointer = fopen("sudokuchar.txt", "r");
if(fpointer == NULL) {
fprintf(stderr, "Error: [Errno %d]: %s\n",
errno, strerror(errno));
return 1;
}
It is advisable to check what file pointer returns. If file pointer returns 0 or NULL then File pointer is unable to point to the file name you had provided. Also you can use this
File *fp = fopen(file name with full path (i.e. /home/chex/read.txt),"r")
Check man fopen
FILE *fopen(const char *path, const char *mode);

how would i use fopen() to accept an argument from a function (c programming)

Example:
void readDoc(FILE *doc_file) {
}
How can I get fopen to read the doc_file when the notation requires you to know the document name before hand because in this case the file name is an argument in the readDoc function.
You don't need fopen because fopen is used to open a file and return a FILE* for that file.
In the code you have shared, you seem to already have a FILE* with you as a parameter.
So you just need to use any read (fread,fscanf,fgets etc.) functions to read the file.
However, you need to ensure that fopen is called on the file you need to read and the FILE* which is returned is passed to the readDoc function.

freopen or freopen_s, what exactly are they doing?

errno_t freopen_s ( FILE** pFile, const char *path, const char *mode, FILE *stream );
Here, the freopen_s disassociates the FILE pointer stream from whatever it is pointing at, then associates it with the file that is located at path. The mode defines the limits for what could be done with this specific pointer stream.
As far as I can tell, all these are nothing different than what would happen with:
...
fclose( stream );
fopen_s( &stream, path, mode );
...
My question is: What does the pFile do there? freopen also has it, as the return value. From all the examples I have seen, pFile, after the call, also points at the same file that is located at path. So:
...
fclose( stream );
fopen_s( &stream, path, mode );
fopen_s( pFile, path, mode );
...
Is this really it?
When you continue reading the help that is referenced in your question you find the answer:
`freopen_s` is typically used to redirect the pre-opened files stdin, stdout,
and stderr to files specified by the user.
So it is not intended that you use a self defined FILE pointer to freopen. Instead it affects the probably widely spreaded used stdout etc.
Regarding your question "Is this really it?": yes.
Edit: Regarding the other question:
My question is: What does the pFile do there?
The pFile parameter to the function freopen_s is a pointer to a FILE*. The function can allocate a new FILE object an return the new pointer with pFile. There might be run-time libraries that doesn't allocate a new object but change the FILE structure that is passed indirectly by *pFile. But this is strongly implementation dependent.
Further the non-atomic operation may fail after the fclose part. In that case the run-time may change the pointer that is passed with pFile to NULL.

C - fopen invalid file

I am wondering, how to check if I am opening file which exists with fopen? I want to diplay some message, when user selects file with bad name. Is must be some simple checking, but I am not able to solve it.
Thanks
in your param list:
FILE pFile ;
then:
pFile = fopen ("myfile.txt","r");
if (pFile == NULL)
printf("No Such File !! ");
When fopen fails, it returns NULL and sets errno to indicate the type of error.
Check the return value, and if it's NULL check errno. You can use functions like perror or strerror to display simple messages about those errors.
To make it even clearer:
f = fopen("some-file-name.ext", "r");
if (f == NULL) reporterror();
But, probably you don't want to use fopen for checking existence and access right. You should look at stat and access. Both available in C libraries and using man
See the possible errors for open:
However, I think you'll have a hard time finding a way to determine that a filename was invalid. On most systems (except Windows) any string that's not overly long is potentially valid (modulo / being interpreted as a path separator).
fopen() function opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.
FILE *try_to_open = fopen("Document.txt", "r"); //READ ONLY
If the file is successfully opened, function returns a pointer to a FILE object that can be used to identify the stream on future operations; otherwise, a null pointer is returned. So, if you want to check that file has been opened correctly, just check that pointer is not null, in this way:
if (try_to_open == NULL){
puts("Opening file failed.");
} else {
puts("File opened successfully.");
It's simple: the returned FILE* pointer will be null if file doesn't exists.
Of course this assumes you are opening it in r, read mode.

How do I open a file in such a way that if the file doesn't exist it will be created and opened automatically?

Here's how I open a file for writing+ :
if( fopen_s( &f, fileName, "w+" ) !=0 ) {
printf("Open file failed\n");
return;
}
fprintf_s(f, "content");
If the file doesn't exist the open operation fails. What's the right way to fopen if I want to create the file automatically if the file doesn't already exist?
EDIT: If the file does exist, I would like fprintf to overwrite the file, not to append to it.
To overwrite any existing file, use the creat call:
#include <fcntl.h>
#include <stdio.h>
int fd = creat (fileName, 0666); // creates file if not exist, overwrite existing
FILE *f = fdopen (fd, "w"); // optional, if FILE * type desired
Did you try just doing fopen(name, "w")? Also, you should perhaps extend your code to report what error is being signalled, using e.g. perror().
Note
Incidentally, I would avoid (at least most of) MSVC's _s functions despite the warnings. There's very little point in the first place except when:
The original function either writes to a passed-in buffer, but does not have a parameter to specify the size of the buffer (e.g. strcat()), or
The original function was permitted/required to return a pointer to a static buffer (e.g. strerror()), which makes
and these functions are non-portable. In short, most of these functions (including fopon_s()) are gratuitously non-portable -- using them makes your program less portable but gives no benefit. (The incompatible addendum for C can only make things worse -- unless MS implements it, in which case it might only make things more confusing.)

Resources