Unable to access file from share drive using fopen in C (windows) - c

I am taking share drive path as input and adding extra '\' and assigning to a variable.If I use this variable for opening file with "fopen" error is thrown as "No such file or directory".
But If I give the same path (with extra '\' in the path) in the code itself I am able to access.
command: program \\xyz\abc.txt (program_name )
1) My code which doesn't work is like this:
In the program I am making the passed in input path as "\\\\xyz\\abc.txt" by adding extra "\".
then, fopen(var_name,"r"); /* Not working*/
2) Code which works fine:
char arr[100] = "\\\\xyz\\abc.txt"
fopen(arr,"r"); /* works fine */
It seems if the path is known at compile time itself it is working but not at run time.Please suggest what can I do to access path from input not hard coded in program.

You need to escape the backslash in filepath during compile time.. i.e.
"\xyz\abc.txt" but runtime has only one slash.
Piece of code to read input from user:
char filename[50];
FILE *fp;
printf("Enter the filename \n");
gets(filename);
fp = fopen(filename, "r");

Related

Fopen - No such file or directory in C

This code does not open file properly, it returns no such file or directory, although the path and privilege are there and no other program is using the file. How can I fix the error? I tried swapping the path and moving the file, the error is there still.
char string[105];
FILE* file = fopen("C:\\Users\\Public\\Documents\\a.txt", "r");
while (fgets(string, 100, file)) {
printf("%s", string);
}
It can be surprisingly tricky to open a simple file! Lots of things can go wrong. I recommend writing slightly more verbose code, like this:
#include <string.h>
#include <errno.h>
char* filename = "C:\\Users\\Public\\Documents\\a.txt";
char string[105];
FILE* file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "can't open %s: %s\n", filename, strerror(errno));
exit(1);
}
while (fgets(string, 100, file)) {
printf("%s", string);
}
The point is that the error message prints out both the name of the file it tried but failed to open, and the actual reason it couldn't open it. (Also, by storing the filename in a variable, you make it absolutely certain that the filename it prints in the error message is the filename it tried but failed to open.) It sounds like you already know that the error was "no such file or directory", but I'm not sure how you know this.
Even though I've been programming in C for a long time, sometimes I still have this problem. One thing I'll sometimes do is use my mouse to copy the exact filename string printed in the error message, the file the program said it couldn't open, the file I'm sure is really there, and paste it into a terminal window (or CMD or Powershell if you're on Windows), along with a directory-listing command, to see if the operating system can actually see the file. That is, for your example, the command I'd run is
dir C:\Users\Public\Documents\a.txt
but the point is that I would not actually type the pathname "C:\Users\Public\Documents\a.txt", instead I would copy and paste it out of the error message that the program printed. Sometimes there are surprising little impossible-to-spot differences between the filename you thought it was trying to open, versus the filename it was actually trying to open, and this exercise is a good way to let the computer help you find those differences.
Remember, too, that you'll get the error "No such file or directory" if there's no file by that name in the directory, or if the directory isn't there at all. For example, if you're trying to open the path
C:\Users\Public\Documents\a.txt
and the file a.txt keeps not being there, and you keep checking your home directory
C:\Users\Donkey\Documents
and you keep seeing that the file is there, it can be surprisingly easy to overlook what the real problem is. :-)
Addendum: You might be having an issue with the different Unix/Linux versus Windows file path separators, that is, / versus \. Usually, on a Windows machine, it's safest to use \, as you've done. (One very frequent mistake is to forget to double the backslashes, but it looks like you got that right.) Depending on your programming environment, if there's some level of Unix emulation going on, you can sometimes use Unix-style /, and it will automatically translate to \ for you. I've never heard of a situation where using \ made it not work (which is a possibility being explored in the comments), but you might experiment with that, perhaps trying
char* filename = "/c/Users/Public/Documents/a.txt";
or (less likely)
char* filename = "C:/Users/Public/Documents/a.txt";

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

Even after providing proper path in the program , I can not open the file in Visual C++

I have written a simple C code in visual C++
I am planning to open a text file for reading , but whenever i enter path it shows "unable to open the file".
then i hardcoded the path in the program itself. still same error , can anyone tell me what I am doing worng ? or where I wil have to copy paste that file so that i can open it in visual c++ through my code ?
here is my code :
#include<stdio.h>
#include<conio.h>
int main(){
FILE *p;
char file1[20];
char ch,i;
printf("\nEnter the source file name to be copied:");
gets(file1);
p=fopen(file1,"r"); // I have tried changing it with actual path to the file
if(p==NULL)
{
printf("cannot open %s",file1);getch();
exit(0);
}
while((i=getc(q))!=EOF)
printf("%c",i);
fclose(p);
return 0;
}
Save one file in your directory where you have saved the program.
And try it typing the perfect full name of the file including format of the file.
Your code seems error free.
When you're telling directory during execution use // only dont use / otherwise it will show you error and file won't open.
it worked after Entering double back slash "\\" instead of single back slash after the Drive name (example "c:\\") for the path to the file.

How to read file from local directory path

I have one function which reads file and does the conversion part.
fp=fopen("newfile.txt","r");
Here i have copied this newfile.txt in project file and compiling in VC++ 2008 IDE.It works fine
I would like to read the file from a local drive directory path.is it possible to read the files from local drive.how to mention the path.If so please mention any example.
one more thing If i want to read all the files in that particular folder with out changing the name of text files in the above code. Suggest me any thing to do.
I dont want to change the file name manully in the code
You could use an absolute path to your file:
FILE* fp = fopen("c:\\your_dir\\your_file.txt", "r");
if(fp) {
// do something
fclose(fp);
}
or a relative path, assuming your file is located in c:/etc and your executable is located in c:/etc/executables:
FILE* fp = fopen("..\\your_file.txt", "r");
if(fp) {
// do something
fclose(fp);
}
I think you can use first program argument. It is a string containing path of executable. You can access it by usingint main(int argc, char *args[]) instead of int main(). The args[0] contains what you need. Just take a substring of it, to get the path and concatenate it with your filename.

Where is a file placed when it is created like this?

How can I see where the file is created and open it?
#include <stdio.h>
int main ()
{
FILE * pFile;
char sentence [256];
printf ("Enter sentence to append: ");
fgets (sentence,255,stdin);
pFile = fopen ("mylog.txt","w");
fputs (sentence,pFile);
fclose (pFile);
return 0;
}
The file will be created in your current working directory.
Should find it in the directory you run the app from
The file will be create in the same directory the executable program is in.
you can open the same way you create it, changing the options to the fopen,,
FILE *inp;
inp = fopen("FileName","r");
// Do what you want
fclose(inp);
File is created in the same directory as the source code/C File because here you're giving relative path. If you want to put the file somewhere else, you can try giving Full path instead of relative one.
The file should be automatically created in your working directory (where you run the program from). You can open it in any text editor to make sure it was written properly.
If you meant how do you open it in the code, change "w" to "r".

Resources