fopen failed with my file path - c

Trying to open and write to the following file path, for some reason it is not opening, I've tried several different paths and nothing has worked. I am running this from C:\
FILE* fptwo = fopen("\\C:\\Program Files\\NotMal.txt", "w");
if (fptwo != NULL)
{
printf("open progfiles successful \n");
//add this text to the file
fprintf(fptwo, "This is text");
printf("add text succuessful \n");
//close file pointer when finished
fclose(fptwo);
}
*please feel free to delete or close this question if it is answered somewhere else, I apologize for the mistakes made within this, and if it is a stupid error.

You test if you have correctly opened the file, it's good !
But it's better to know why your function call have failed.
For "fopen", you can know by looking the value of errno. (read the man about fopen).
And a "cool thing" is that you can obtain an english description by using "strerror".
So, just do :
#include <string.h> // For strerror
#include <errno.h> // For .... errno
FILE* fptwo = fopen("\\C:\\Program Files\\NotMal.txt", "w");
if (fptwo == NULL)
{
printf("Error : errno='%s'.\n", strerror(errno));
}
else
{
printf("open progfiles successful \n");
//add this text to the file
fprintf(fptwo, "This is text");
printf("add text succuessful \n");
//close file pointer when finished
fclose(fptwo);
}

Program Files is windows default software deployment folder. Better not to use that path. Better create your own test folder and test. If possible not to name folder with space.
FILE* fptwo = fopen("C:\\MyProject\\test\\NotMal.txt", "w");

Related

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.

Writing the correct path in fprintf function

Apparently, there's no data regarding my question (I tried searching it out here but none of the threads I've read answered my doubt). Here it is: I'm trying desperately to figure out how can I put a correct path into the fprintf function and none of my tries have been successful. Here's the program:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp = NULL;
//opening the file
fp = fopen("C:/Users/User1/Desktop/myfile.txt", "w+");
//if there's an error when opening the file, the program shuts down
if(fp == NULL){
printf("error");
exit(EXIT_FAILURE);
}
//print something on the file the program just opened (or created if not already existent)
fprintf(fp, "to C or not to C, that is the question");
//closing the file
fclose(fp);
//end of main function
return 0;
}
My question is: why my program always shuts down? What am I doing wrong? It's just a Windows problem (I saw that, on the User1 folder icon, there's a lock, could be a permission denied thing?) or I'm just putting the path in an incorrect way? I tried to use a string to save the path, I tried to change the opening mode, I even tried to disable all the antiviruses, antimalwares and firewalls I have installed on my computer but nothing, the program still doesn't create the file where I want it.
P.S. Sorry for bad English.
P.P.S. Sorry if a similar question has been already posted, I didn't manage to find it.
fp = fopen("C:\Users\User1\Desktop\myfile.txt", "w+");
The character \ is the escape character in C. You must escape it:
fp = fopen("C:\\Users\\User1\\Desktop\\myfile.txt", "w+");
Even better, windows now supports the / directory separator. So you can write:
fp = fopen("C:/Users/User1/Desktop/myfile.txt", "w+");
With no need to escape the path.
Reference:
MSDN fopen, specifically the Remaks section
Use perror() to have the Operating System help you determine the cause of failure.
#define FILENAME "C:/Users/User1/Desktop/myfile.txt"
fp = fopen(FILENAME, "w+");
// report and shut down on error
if (fp == NULL) {
perror(FILENAME);
exit(EXIT_FAILURE);
}

Won't create txt file C program

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.

Why does "w" in fopen here not create a new file?

The program always ends up exiting. I seem to be running in to this problem frequently and I think I somehow previously fixed it but I'm not sure how. Why does it not create a file?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (void){
FILE *fp;
int c;
char file_w[100];
char string[100];
printf("Enter filename\n");
fgets(file_w, 100, stdin);
fp = fopen(file_w, "w");
if (fp == NULL){
printf("Can't open file\n");
exit(0);
}
printf("Enter a string");
fgets(string, 100, stdin);
for(c = 0; c <= sizeof(string); c++)
{
fprintf(fp, "%s\n", string);
}
printf("file written");
fclose(fp);
return 0;
}
Try to print the name of the file you have entered:
printf("%s\n", file_w);
just after the line you get file_w, just to be sure to enter what you want. I same cases the terminal could be wrongly configured.
Try to enter an absolute name path, if your computer is a Linux or Unix:
/tmp/newfile.txt
If your computer is Windows... Well try to see if C:\temp\ exist (or create it) and then enter:
C:\temp\newfile.txt
In any case, remember that you can specify an absolute path, and not only the file name. So double check if you have the rights (i.e. the permissions) to write into the directory where the file should be written.
In case you want check the error and have a better description of the problem try to use the following lines instead of your code, just under the fopen
if( fp == NULL ) {
// Error, as expected.
perror( "Error opening file" );
printf( "Error code opening file: %d\n", errno );
printf( "Error opening file: %s\n", strerror( errno ) );
exit(-1);
}
strerror it is a wonderful function just because return you a description of the problem instead of an error code.
I bet the problem is "invisible character after actual name from fgets()". I'll let you figure out exactly what that character is, where it comes from and how to fix it, as "struggling to solve a problem" is part of the learning process when it comes to programming. If it was easy, everyone could do it.
If the return value of fopen is NULL it means some error occurred. I suggest you look into the errno global to see what error has occurred to help you debug why it's not opening the file.
The w flag does the following:
write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
So it should create a file when none exists, or when it does exist, overwrite its content.
If it does not do that, you have another problem, but from the little information you've given, it's hard to tell what it is.
I tried as a name of file the following:
C:\\temp\\test_file.txt
or
fopen("C:\\temp\\employees.txt", "w");
and it works fine, without errors (I made it in Windows 10. GCC win32, Version: 6.3.0).
I think that you have to use an absolute path to create the file.
use gets() instead of fgets()...it will work
.
.
gets(file_w);
.
.

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...

Resources