C open file using a function [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am pretty new to C and I am struggling to write to files form my C program. In this program I open files to read from as well as files to write to, so I thought I'll make a function that opens the file for me. This is what I did
FILE *open_file(char* filename, char* mode)
{
FILE *f;
f = fopen(filename, mode);
if(!f)
{
perror(filename)
exit(EXIT_FAILLURE);
}
return f;
}
And this is how I call the function:
FILE *infile = open_file(args.infile_name, "r");
FILE *rm_file = open_file(args.rm_file, "r");
FILE *ex_file = open_file(args.ex_file, "w");
Those function calls are spread throughout the program. first I had the mode "r" hardcoded in there because I only needed to read from files, but now I also want to write for a file, so I made a parameter for the modus in which the file should be opened. It worked fine before, but now it does nothing. I compiles fine, without any errors, warnings and/or notes. Also valgrind tells me that everything is fine. Any thoughts on this? Thanks in advance.
EDIT: I forgot to add the line where I returned f, I added it now. It was in my code already (ofcourse, you can't let a non void function return nothing).
EDIT: Better explanation of the "error": I am trying to read words from a file and store them in a tree like datastructure. This is working fine, I can look them up and all so no problems here. After adding words to the tree I print the amount of words found in the file and the amount of words added to the tree (I don't add words that are already there). Now I want to export the tree to a file so I need to open a file I can write to. Since I had hardcoded the open_file with the read-only modus, I added a parameter for the modus. But when I run the program now it gives no error (so the filepointer isn't NULL) but just says 0 words found in file and 0 words added. Also the file I print to stays empty. Hope this makes it a little clearer

FILE *open_file(char* filename, char* mode)
{
FILE *f;
f = fopen(filename, mode);
if(!f)
{
perror(filename)
exit(EXIT_FAILLURE);
}
}
Your function doesn't return anything. Simply add return f; at the end. Seems your wrapper is doing little work though, could have also put this code where you are using it directly, instead of having this function.

Related

problem in using fprintf_s(getting warnings) in c

I'm new in c.I just want to complete my project.a list of student with struct.and one of the option is save data in a file.
I using visual studio 2022 and BTW I can't use syntaxs like scanf or something like that.I have to use scanf_s and etc
anyway for fprintf_s I don't know how can I use it for my project.I searched in stackoverflow and another sites about it syntax but they were not usefull, but vs gives me a warning. it is:
sttp could be '0'
the source code is :
FILE* sttp;
fopen_s(&sttp, "text.txt", "w");
fprintf_s(sttp, "test");
fclose(sttp);
and there are some warnings the image of error list
When you try to open a file with fopen_s function, it may or may not succeed, so you must check the return value of that invocation.
If for some reason, the file was not opened, then your file pointer variable, sttp will not be initialized, hence the VS IDE is showing you the warning.
Modify your code, like below.
FILE* sttp;
if(0 == fopen_s(&sttp, "text.txt", "w") )
{
fprintf_s(sttp, "test");
fclose(sttp);
}

Writing in the executable while running the program

I'm writing a C program and I would like to be able to store data inside the executable file.
I tried making a function to write a single byte at the end of the file but it looks like it can't open the file because it reaches the printf and then gives "segmentation fault".
void writeByte(char c){
FILE *f;
f = fopen("game","wb");
if(f == 0)
printf("\nFile not found\n");
fseek(f,-1,SEEK_END);
fwrite(&c,1,sizeof(char),f);
fclose(f);
}
The file is in the correct directory and the name is correct. When I try to read the last byte instead of writing it works without problems.
Edit: I know I should abort the program instead of trying to write anyway but my main problem is that the program can't open the file despite being in the same directory.
There are several unrelated problems in your code and the problem you're trying to solve.
First you lack proper error handling. If any function that can fail (like e.g. fopen) fails, you should act accordingly. If, for example you did
#include <error.h>
#include <errno.h>
...
f = fopen("game","wb");
if ( f == NULL ) {
error(1,errno,"File could not be opened");
}
...
You would have recieved an useful error message like
./game: File could not be opened: Text file busy
You printed a message, which is not even correct (the file not beeing able to be opened is somthing different, than not beeing found) and continued the program which resulted in a segmentation fault because you dereferenced the NULL pointer stored in f after the failure of fopen.
Second As the message tells us (at least on my linux machine), the file is busy. That means, that my operating system does not allow me to open the executable I'm running in write mode. The answers to this question lists numerous source of the explanation of this error message. There might be ways to get around this and open a running executable in write mode, but I doubt this is easy and I doubt that this would solve your problem because:...
Third Executable files are stored in a special binary format (usually ELF on Linux). They are not designed to be manually modified. I don't know what happens if you just append data to it, but you could run into serious problems if your not very careful and know what you're doing.
If you just try to store data, use another plain and fresh file. If you're hoping to append code to an executable, you really should gather some background information about ELF files (e.g. from man elf) before continuing.

fopen ordering in C affecting it strangely [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this code:
FILE *setup=fopen(strcat(cwd,"setup.txt"),"r");//navigates up to setup file
...//(doing stuff with setup)
fclose(setup);
FILE *paths=fopen(strcat(cwd,"stuff.txt"),"r");
char buff2[1024];
fgets(buff2,200,paths);
char thing[1024];
strcpy(thing,buff2);
printf(thing);
fclose(paths);
but it executes differently based on if I do code with setup or the code with paths first - only the first one works properly, the second just creates gibberish whenever fgets is called. fclose returns 0 as it should. The specific way I look at the second file doesn't seem to affect it. What's happening here?
Don't strcat()!
FILE *setup=fopen(strcat(cwd,"setup.txt"),"r");//navigates up to setup file
// cwd now has "...setup.txt"
FILE *paths=fopen(strcat(cwd,"stuff.txt"),"r");
// cwd now has "...setup.txtstuff.txt"
strcat() modifies cwd.
So if cwd originally contains "/home/username/", the first call changes it to "/home/username/setup.txt".
The second call appends to that, so it tries to open "/home/username/setup.txtstuff.txt". This filename almost certainly doesn't exist, but you aren't checking for an error.
And if that filename is longer than the space allocated to cwd, you'll get a buffer overflow and undefined behavior.
Use a different variable to hold the filename to open.
char filename[MAXLENGTH];
sprintf(filename, "%s%s", cwd, "setup.txt");
FILE *setup = fopen(filename, "r");
...
fclose(setup);
sprintf(filename, "%s%s", cwd, "stuff.txt");
FILE *paths = fopen(filename, "r");
...
fclose(paths);

Why C is creating an empty text file

I'm trying to write my results to a text file so I can use MATLAB for plotting and etc. and the code has no problem (i tried with just showing the results with fprint), but now that i'm trying to save the resutls to a text file, C creates the file names amiir.txt, but it is empty. Even if I use relative directories, the text file will be empty. I tried to create a text file and then run the code again, but it is empty!
whats wrong?
I am using mac os and i tried both XCode and CodeLight!
thanks.
P.S.: Here is a piece of my code:
FILE * fp; /* open the file for writing*/
fp = fopen ("/Users/amirsmacbookpro/Documents/Heat_Transfer/Project/Debug/amiir.txt","w+");
anf after some calculations:
for(i=0;i<Total_Nodes;i++)//Error
{
if(Temps_Diff[i]>Calculated_Error) Calculated_Error=Temps_Diff[i];
}
printf(fp,"\n%.4f",Calculated_Error);
// printf(fp,"\n\nROW\tColumn\tTemp\n");
for(i=0;i<=a/l;i++)//Showing results
{
for(j=0;j<=i;j++)
{
printf(fp,"%d\t%d\t%.6f\n",i,j,Temperatures[i][j]);
}
}
}
fclose(fp);
You need to use fprintf instead of printf. The printf function just prints to the console, not to a file.
Note that your compiler should be complaining (perhaps with a warning?) about your use of printf. The printf function does not take a function pointer as the first argument. You may need to turn up your compiler warning level to see this warning.

Error opening file

RESOLVED. Problem -
The lecturer uploaded a text file called file.txt and this resulted in a file "file.txt.txt"... I am feeling a mix of frustration and stupidity right now.
Original problem
I'm having trouble with C using Visual Studio 2012 on Windows 7 trying to open a text file using fopen. I'm not too sure which directory this file.txt should be in so I tried placing it with the .vcxproj file AND the .exe file which is in the Debug directory created by VS.
With no success, I tried including the full path to the file in the fopen function.
This code compiles fine but when I run it, I get an error saying "No such file or directory"
What am I doing wrong and how can I fix it? I'm really confused here and any help would be most welcome! Thanks in advance.
Code below:
int main(void)
{
FILE *fp;
fp = fopen("C:\\Directory\\file.txt", "r");
if (fp == NULL)
{
perror("Error opening file\n");
}
return 0;
}
Do you really have any file at this place "C:\Directory\file.txt" I guess you do not have one.
I tried the code and it runs perfectly fine for me. Initially I was getting the same error and that was because the file was not there. Once I put the file there, it all worked perfectly as expected.
Please check again that the file is in place.
You should include the proper header for fopen(), which is
#include <stdio.h>
Make sure all the backslashes are really escaped (doubled) in your filename, too.

Resources