How to read and write a file which is not in the bin directory that is it is out of the C drive.
I wrote this code
fs=fopen("d:/source.txt","w");
if(fs==NULL)
{
puts("Unable to open file");
}
And it is outputting "Unable to open file". Can someone please help me out.
FILE *fs= fopen("d:/source.txt","w");
if(fs==NULL)
{
printf("can't open");
}
if (fs!=NULL)
{
fputs ("Opened successfully",fs);
fclose (fs);
}
Make sure the source.txt file exists and it is not read only. I tried above code didn't get any error.
There are several possible reasons why the file cannot be opened via fopen().
To get information on details of the error print out errno and/or call perror() and/or strerror() like for example so:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
char filename[] = "d:/source.txt";
FILE * fs = fopen(filename,"w");
if (NULL == fs)
{
perror("fopen() failed");
fprintf(stderr, "Error #%d occurred when trying to open file '%s': %s.\n",
errno,
filename,
strerror(errno));
}
...
return 0;
}
Related
I've written the following code below and ran it without errors on both xcode and vscode. However, I wasn't able to get any output filename.txt. It wasn't in any of my folders.
Appreciate if anyone could help.
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp=NULL;
fp = fopen("filename.txt","w+");
if (fp!= NULL){
fprintf(fp,"%s %d","Hello",555);
}
fclose(fp);
return 0;
}
ran it without errors
fclose(NULL) is undefined behavior (UB), so it is not clear that there was no error when file failed to open.
Print something in both cases of opening success/failure - and with a '\n'. Useful to add error info.
Robust code checks all I/O operations.
#include <stdio.h>
#include <string.h>
int main() {
const char *filename = "filename.txt";
FILE *fp = fopen(filename,"w+");
if (fp == NULL) {
fprintf(stderr, "Unable to open <%s>\n", filename);
perror("fopen()");
} else {
printf("Success opening <%s>\n", filename);
if (fprintf(fp,"%s %d","Hello", 555) < 0) {
fprintf(stderr, "Print failure with <%s>\n", filename);
perror("fprintf()");
}
if (fclose(fp) == EOF) {
fprintf(stderr, "Failed to close <%s>\n", filename);
perror("fclose()");
}
}
return 0;
}
I've also tried the perror method and it shows filename.txt: Permission denied. Later.
Check if filename.txt is read-only, or in use by another application (editor?), or other permission limitations.
If the file wasn't successfully opened, then the code does nothing (apart from closing a null FILE-pointer, which is undefined). You should use perror() to indicate why it couldn't be opened:
const char *const filename = "filename.txt";
FILE *const fp = fopen(filename, "w+");
if (!fp) {
perror(filename);
return EXIT_FAILURE;
}
fprintf(fp, "%s %d", "Hello", 555);
There's a good chance that you have an existing filename.txt that isn't writable by you, or you are in a directory where you can't create a new file, but we'll need the error message to actually determine why it wasn't opened.
Alternatively, you're running in a different working directory to where you thought you were - that's something you should investigate (perhaps produce some logging to stderr to indicate where the file is being created).
I ran your code and it works just finecheck this image
but, how are you compiling it and did you remember to run the a.out/execution?
I want to do a error check in a openFile Function in C and on errno:2 I want to recursivly call again the same function.
I don't get the right answer, if I want to do fputs() after opened the file I get a Error (Bad file descriptor)
Here is my code:
void openFile(FILE **fstream, char* path, char* mode) {
*fstream = fopen(path, mode);
if(*fstream == NULL) {
printf("\nError number %2d : ",errno);
perror("Error opening file: ");
switch (errno) {
case 2:
printf("Creating file %s now...\n", path);
*fstream = fopen(path, "a+"); //Creating file in append-mode
if (fstream == NULL) {
perror("Couldn't open the file!\nError");
exit(EXIT_FAILURE);
}
fclose(*fstream); //Closing filestream
openFile(fstream, path, mode); //Recursive call of openFile() to re-open in read-mode
/* freopen(path,mode,fstream) */ //Doesn't work either
break;
default:
exit(EXIT_FAILURE);
break;
}
} else if (*fstream != NULL) {
printf("Successfully opened %s\n", path);
}
}
The call:
openFile(&fp, path,"r");
if (fputs("blabla\nblabla\n",fp) == EOF) {
perror("Unable to write file with fputs()");
}
What I'm doing wrong? I think it's at the point of the recursive call of the function, but what I have to do here? I don't get it..
Output is:
> .\a
Content of path: test.txt
Error number 2 : Error opening file: : No such file or directory
Creating file test.txt now...
Successfully opened test.txt
Unable to write file with fputs(): Bad file descriptor
PS: I am a beginner with C, I've read and youtubed a lot about pointer, but I don't get the mistake.
Thank you in advance
You opened the file with "r" yet you're attempting to write. You need "w" instead.
I tried to create a file and I did.
Now I'm trying to create the file inside a new folder, but this code doesn't work!
#include <stdio.h>
#include <stdlib.h>
int main( void)
{
FILE *fp;
fp = fopen("txt/example.txt", "w"); // This only works without "txt/"
fprintf(fp, "%s", "Some data here");
fclose(fp);
return 0;
}
Maybe I need to create the folder before and only after the file, but I don't know how to achieve it... any help is appreciated!
This example makes the directory before it creates the file, and when it makes the file, note the double \\ in the file name to prevent an escape sequence being attempted from \e, although it does work with a single / too.
#include <stdio.h>
#include <direct.h>
#include <stdlib.h>
void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}
int main(void) {
FILE *fp;
if (mkdir("txt"))
fatal ("Error creating directory");
if ((fp = fopen("txt\\example.txt", "w")) == NULL)
fatal ("Error opening file");
if (fprintf(fp, "%s", "Some data here") <= 0)
fatal ("Error writing to file");
if (fclose(fp))
fatal ("Error closing the file");
return 0;
}
You need to use CreateDirectory to create a directory on windows.
I created a text file named "test.txt" and then executed this program to copy the contents of "test.txt" to "file.txt". But it is showing an error while opening the file itself, i.e., fr==NULL is true.
What is wrong with the program?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int i,count=0;
char ch;
FILE *fw,*fr;
fw = fopen("file.txt", "a+");
fr = fopen("test.txt", "r+");
fseek(fr,0,SEEK_SET);
if(fr==NULL)
{
printf("Error while opening the file.\n");
exit(0);
}
while((ch=getc(fr))!=EOF)
{
putc(ch,fw);
}
fclose(fw);
fclose(fr);
return 0;
}
If fopen returns NULL, check the value of errno, e.g. by including <errno.h> and using the perror("Error while opening the file"); instead of the printf statement.
I have created a program that sequentially displays on screen the contents of all of the files listed in the command line.
However, when I run it in terminal I can't actually get it to open any files I try to "feed" it.
Does anyone know how I can get it to work?
Here is an example of what I'm typing into Terminal on my mac:
"John_Smith-MacBook:Desktop smith_j$ "/Users/smith_j/Desktop/Question 3-28-13 5.10 PM/usr/local/bin/Question" helloworld.txt
Could not open file helloworld.txt for input"
This is the first day I've ever used Terminal so forgive me if the answer is very easy.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int byte;
FILE * source;
int filect;
if (argc == 1)
{
printf("Usage: %s filename[s]\n", argv[0]);
exit(EXIT_FAILURE);
}
for (filect = 1; filect < argc; filect++)
{
if ((source = fopen(argv[filect], "r")) == NULL)
{
printf("Could not open file %s for input\n", argv[filect]);
continue;
}
while ((byte = getc(source)) != EOF)
{
putchar(byte);
}
if (fclose(source) != 0)
printf("Could not close file %s\n", argv[1]);
}
return 0;
}
Look at the value of errno [probably with perror() ] so you know why it is failing to open.
Simple example:
perror("fopen failed:");
printf("errno = %d.\n", errno);
It will prefix the text version of the errno condition (library supplied) with "fopen Failed: ", then give the specific errno value.
The text of your command line above looks suspect, check to see if it is correct. Better yet, try calling your program with a simpler command line, for example, one file in the current directory with your binary.
Instead of all the long pathnames, put both the binary program and the data file in the same directory together. Then, from that location just do ./myprog filename.txt
That will have less chance of a typo interfering with execution.