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?
Related
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
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.
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;
}
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.