problem in using fprintf_s(getting warnings) in c - 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);
}

Related

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.

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.

C open file using a function [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 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.

Netbeans and C, peculiar bug

I am writing something in C using Netbeans 6.9.1 (its a requirement) and I stumbled upon a peculiar bug. When I try to run this code from Netbeans:
#include <stdio.h>
#include <stdlib.h>
#include "company_description.h"
company_description read_company_description() {
char file_name[FILE_NAME_BUFFER_SIZE];
FILE *company_description_file;
company_description cd;
printf("Please enter the name of the file containing the "
"company's description: \n");
scanf("%50s", file_name);
company_description_file = fopen(file_name, "r");
if(company_description_file != NULL) {
printf("file is not null\n");
}
fscanf(company_description_file, "%s%s%s%s%s%s", cd.company_name,
cd.name_file_deliveries_info, cd.name_file_industrial_park,
cd.name_file_places, cd.name_file_roads, cd.name_file_vans_info);
return cd;
}
I get this output:
Please enter the name of the file containing the company's description:
name_file.txt
Segmentation fault
Press [Enter] to close the terminal ...
Ok I say to myself, from my point of vie there is nothing wrong with this code and I go to
~/path/to/NetbeansProject/dist/Debug/GNU-Linux-x86 and try to run the executable from there and it works. I forgot to mention that the file that should be read is in that same folder, exactly where the executable is. Now there might be a mistake on my side but I don't see it so any thoughts about this would be helpful. Thanks!
As to why it doesn't run in Netbeans: working directory is probably incorrect - when you run from Netbeans, the working directory is not necessarily the same as where the executable resides.
I do not have Netbeans installed, but you can set the working directory (what directory the system thinks the executable was executed in) in your project's settings.
I also agree with aschelper's answer - if you don't get a valid FILE * back you don't want to continue running that file code.
Your code will probably crash if fopen fails. Sure, you have a check for whether company_description_file != NULL, but then if it is null you go ahead and pass it to fscanf anyway (rather than exit()ing or returning early or something). Undefined Behavior.
Don't blame the compiler/IDE, the bug is in your code :)
company_description_file = fopen(file_name, "r");
if(company_description_file != NULL) {
printf("file is not null\n");
}
fscanf(...
There is an else missing that will cope with the situation when the file is not found. Right now you pass a NULL pointer to fscanf which causes the crash. Your program cannot find the file most probably because NetBeans sets the working directory somewhere else. Make sure you set the correct working directory or copy the input file to the proper location.

Save file with C fopen

I did a program in C but it does not allow to save on c:\SomeDirectory\afile.txt
I'm using this:
FILE* m_hFile = fopen("c:\\SomeDirectory\\afile.txt", "a+t");
fprintf(m_hFile, "testing");
fclose(m_hFile);
Why that? Is there a defined folder I can save in?
SomeDirectory is previously created.
I'm using Windows 7 OS.
If fopen encounters an error, it sets the errno variable indicating what error occurred. You can test this, or even simpler, use perror to print out an error message that will tell you what went wrong:
FILE* m_hFile = fopen("c:\\SomeDirectory\\afile.txt", "a+t");
if (m_hFile == NULL) {
perror("fopen");
}
It sounds like perhaps "SomeDirectory" doesn't exist. You can create folders with C++ but you'll want to check if one's already there. Just calling the open command doesn't automagically create the folder. :)

Resources