Opening Files for Edit - c

I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
printf("File could not be opened.\n");
}
return 0;
}

Try moving the test.dat file to the directory where the compiled .exe lives, or if the current directory for the application is somewhere else, place the file in that directory.

When you try to open a file, your OS will look in whatever the process current directory is. This may or may not be the same directory as where your source file lives, depending on your OS and/or IDE.

Are you using Visual Studio? You have to put test.dat into the Debug directory. There are two debug directory in newer version, you have to check that yourself.

You could use the errno to get a hint as to what is going wrong:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> /* new */
int main (void)
{
if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
printf("File could not be opened.\n");
printf("Errno = %d\n, errno) ; /* new */
}
return 0;
}

Related

C - Why fopen doesn't work?

I have this very simple code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE * file_ptr = NULL;
file_ptr = fopen ("file.txt", "r");
if (file_ptr == NULL)
{
puts ("Error!");
return EXIT_FAILURE;
}
else
{
puts ("O.k.!");
}
return EXIT_SUCCESS;
}
Output:
Error!
Why fopen doesn't work? The file is not protected, not opened elsewhere and is stored in the same folder as the *.exe of this program. I also tried it with giving the complete path to the file and with an array, in which the filename is stored. Everytime it puts out "Error!".
What's going on??
I'm using Eclipse Neon.2 Release (4.6.2) with newest cygwin gcc compiler on Windows 10 64bit.
Thank you for your help!
The problem was solved by changing the fopen to
file_ptr = fopen("xxyyzzqq.txt", "w");
and then searching the hard drive to see where the file was created.
Turns out that the file was created in the project source directory, and not the debug directory (where the .exe file is), unlike the old installation which used the debug directory as the working directory.
perror might help.
FILE *file_ptr = fopen("file.txt", "r");
if (!file_ptr) {
perror("fopen");
} else {
printf("It's working!");
}
Similar question: fopen() not working in C

Cannot access file from other drive

I am using windows 7 64bit OS and DOS box turbo C++. I want to write a simple program to read a text file containing a single integer from E drive of my machine. The file name is t.txt. I have written the following code:
#include <stdio.h>
#include <conio.h>
#include <dir.h>
#include <stdlib.h>
int main(void)
{
FILE *input;
int data;
if ( (input = fopen("E:\\t.txt","r")) == NULL)
printf("Error: Unable to open");
else
{
fscanf(input,"%d",&data);
printf("successfully read in %d",data);
}
fclose(input);
input=NULL;
getch();
}
But this program is unable to access the file and every time it gives an output like:
Error: Unable to open
What is the problem with this code?
Please help.
Yes!!! got it.. Thank you Michael. I tried to mount E: in dosbox and it has run fine.
Problem must be with the usage of file path
Solution given below worked with me in Ubuntu
just try it
char *file = "E:\\t.txt";
FILE *fp = fopen(file, "r");
And verify whether you are using the correct path
Have a good day

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.

File I/O management in C

My first post :), am starting out with C language as basic learning step into programming arena. I am using following code which reads string from text file, makes directory with that string name and opens a file for writing in that created directory. But am not able to create a file inside directory made, here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <string.h>
int main()
{
char file_name[25], cwd[100];
FILE *fp, *op;
fp = fopen("myfile.txt", "r");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fgets(file_name, 25, fp);
_mkdir(file_name);
if (_getcwd(cwd,sizeof(cwd)) != 0)
{
fprintf(stdout, "Your dir name: %s\\%s\n", cwd,file_name);
op = fopen("cwd\\file_name\\mynewfile.txt","w");
fclose(op);
}
fclose(fp);
return 0;
}
What you need is to store the file name (with the path) in a c-string before opening. What you are opening is cwd\file_name\mynewfile.txt. I doubt that your directory is named cwd.
A sample could could be:
char file_path[150];
sprintf(file_path, "%s\\%s\\mynewfile.txt", cwd, file_name);
op = fopen(file_path,"w");
use
#include <sys/stat.h>
#include <sys/types.h>
instead of
#include <direct.h>
and modify
op = fopen("cwd\\file_name\\mynewfile.txt","w”);
I see you are using the return values. That is a good start for a beginner. You can refine your error messages by including "errno.h". Instead of printing your own error messages call
printf("%s", strerror(errno));
You get more precise error messages that way.
op = fopen("cwd\\file_name\\mynewfile.txt","w”);
You’re actually passing the string literals “cwd” and “file_name” as part of the path of the file, when I think you actually mean to put the contents of the variables with those names in there. You will probably have to piece together a string for the path. Try looking into strcat()
http://www.cplusplus.com/reference/cstring/strcat/

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