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
Related
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;
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
I'm playing with file I/O in C.. I'm trying to use fgets to read data in from one file and output it to another file. The problem is that it always returns NULL and so nothing gets copied to the output file. Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpIn;
FILE *fpOut;
if ((fpIn = fopen("C:\\testIn.txt", "r") == NULL))
{
printf("Cannot open input file!\n");
exit(1);
}
if ((fpOut = fopen("C:\\testOut.txt", "a") == NULL))
{
printf("Cannot open output file!\n");
exit(1);
}
char buffer[128];
while (fgets(buffer, 128, fpIn) != NULL)
{
fputs(buffer, fpOut);
}
fclose(fpIn);
fclose(fpOut);
system("PAUSE");
return 0;
}
another thing; when I tried using "a+f" in the second arg for fopen, it didn't work.
if ((fpOut = fopen("C:\\testOut.txt", "a") == NULL))
Should be
if ((fpOut = fopen("C:\\testOut.txt", "a")) == NULL)
Same on the input file.
If you are new to C, I'd suggest do one thing at a time to make it easier to track down issues.
e.g.
fpOut = fopen("C:\\testOut.txt", "a");
if(fpOut == NULL) {
...