I am having a small problem, I have the current file structure:
And this is my code:
#include <stdio.h>
#include <stdlib.h>
const char FILE_NAME[] = "inputfile.txt";
int main()
{
FILE *in_file; /* input file */
in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}else{
printf("File opened %s\n", FILE_NAME);
}
fclose(in_file);
return (0);
}
And I get this error:
Cannot open inputfile.txt
But the file is right there.
Can someone help me?
(If I change the "r" to "w" I can write to the file, but I can't find the file on my SSD)
The program will look for the file in the current working directory. This is most likely the same directory as the compiled executable.
If you are using an IDE, check the project settings and check where the compiled executable is placed. Then either copy the textfile to that directory manually or edit the project so that building it copies the file automatically.
If you are working from the command line (assuming your compiler is called gcc):
cd ~/Documents/programming/c/PracticalC/chapter14
gcc -Wall ch14pexercise1.c -o prog
./prog
include
include
const char FILE_NAME[] = "inputfile.txt";
int main()
{
FILE *in_file; /* write file */
in_file = fopen(FILE_NAME, "w");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}else{
printf("File opened %s\n", FILE_NAME);
}
fclose(in_file);
/read file/
FILE *in_file; /* input file */
in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}else{
printf("File opened %s\n", FILE_NAME);
}
fclose(in_file);
return (0);
}
If it work cheak path
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'm trying to create a function that checks if a file exists, if it does then it will open it up in order to update it, and if it doesn't exist it will create a new one.
void readFunc(void) {
FILE *input;
char filename[N];
printf("Write textfile: ");
scanf("%s", filename);
if(input == NULL) {
printf("\nFile doesn't exist. Creating a new one!\n\n");
input = fopen(filename, "w+");
} else {
printf("\nFile exists!\n\n");
input = fopen(filename, "r+");
}
}
This is what my code looks like now. I know it might be very wrong but I would like to know how to think in order for it to work.
I will insert pointers later in order for it to work well with the main function.
Because of TOCTOU races, the best way to do this is to drop down a level and use open, which, unlike fopen, lets you specify "open this file for read and write, preserving existing contents, and create it if it doesn't already exist":
FILE *ensure_file(const char *fname)
{
int fd = open(fname, O_RDWR | O_CREAT, 0666);
if (fd == -1) {
perror(fname);
return 0;
}
return fdopen(fd, "r+");
}
The code is almost correct: you should for try with "r+", then "w+ if the file does not exist:
#include <errno.h>
#include <stdio.h>
void readFunc(void) {
FILE *input;
char filename[256];
printf("Write textfile: ");
if (scanf("%255s", filename) != 1)
exit(1);
input = fopen(filename, "r+");
if (input != NULL) {
printf("\nFile exists\n");
} else {
printf("\nFile doesn't exist. Creating a new one!\n\n");
input = fopen(filename, "w+");
if (input == NULL) {
printf("Cannot create file: %s\n", strerror(errno));
return;
}
}
[...]
}
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 can't figure out why this isn't working.
#include <stdio.h>
int main(void) {
FILE *in, *out;
// char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ ";
// char *mode = "r";
// in = fopen(FULLPATH, mode);
//
// if (in == NULL) {
// perror("Can't open in file for some reason\n");
// exit (1);
// }
out = fopen("C:\\Users\\Jay\\c\\workspace\\I-OFiles\\out.txt", "w");
if (out == NULL) {
perror("Can't open output file for some reason \n");
exit(1);
}
fprintf(out, "foo U");
fclose(in);
fclose(out);
return 0;
}
if I remove the // from the commented lines, the error compiler gives is
: Invalid argument
I don't understand why (I read all the other threads related, and nothing).
It does actually write the out.txt file OK, so it doesn't seem like a path misspelled problem.
Remove backslash after in.txt.
The input file name seems bogus:
"C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ "
The filename is just a single space " " and in.txt is probably not a directory.
Change the code to:
const char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt";
Or preferably:
const char *FULLPATH = "C:/Users/Jay/c/workspace/I-OFiles/in.txt";
for better portability as forward slashes work in Windows as well as in Unix.
Furthermore, it is easy to provide more information as to why fopen() failed to open the files.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *in, *out;
in = fopen("C:/Users/Jay/c/workspace/I-OFiles/in.txt", "r");
if (in == NULL) {
perror("Cannot open input file");
exit(1);
}
out = fopen("C:/Users/Jay/c/workspace/I-OFiles/out.txt", "w");
if (out == NULL) {
fclose(in);
perror("Cannot open output file");
exit(1);
}
fprintf(out, "foo U");
fclose(in);
fclose(out);
return 0;
}
Change backslash to slash.
Maybe you don't have permissions or something like that.
out = fopen("C://Users//Jay//c//workspace//I-OFiles//out.txt", "w");
if (!out)
perror("fopen");
return 0;
Here is a simple program that should copy the content of one
file named copyme into a file here. I have created copyme with a little text in it by the following commands:
touch copyme.txt
open copyme.txt
Then I typed in text, and saved the file with
touch copyme.txt command.
Then I compiled a program:
// Program to copy one file ot another
#include <stdio.h>
int main (void)
{
char in_name[64], out_name[64];
FILE *in, *out;
int c;
// get file names from user
printf("Enter name of file to be copied: ");
scanf("%63s", in_name);
printf("Entere name of output file: ");
scanf("%63s", out_name);
// open input and output files
if ( (in = fopen(in_name, "r")) == NULL)
{
printf("Can't open %s for reading.\n", in_name);
return 1;
}
if ( (out = fopen(out_name, "w")) == NULL)
{
printf("Can't open %s for writing.\n", out_name);
return 2;
}
while ((c = getc(in)) != EOF)
putc(c, out);
// Close open files
fclose (in);
fclose (out);
printf("File has been copied\n");
return 0;
}
And ran it in terminal.
Here is the output:
Enter name of file to be copied: copyme
Entere name of output file: here
Can't open copyme for reading.
The compiler doesn't recognize copyme file, although it is
physically exists in the folder (I see it, I open it, I read
it).
I would be grateful for help. I am new to this things.
Thank you!
change
if ( (in = fopen(in_name, "r")) == NULL)
{
printf("Can't open %s for reading.\n", in_name);
return 1;
}
to
#include <errno.h>
if ( (in = fopen(in_name, "r")) == NULL)
{
perror("Can't open file for reading.\n");
return 1;
}
you will get a human readable message telling you why it cant read the file