Why C is creating an empty text file - c

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.

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.

as400: what is the C equivalent of SNDRCVF

I have a display file for a menu. I successfully made a working CL program which displays the menu and waits for input. Simply enough, all it does is display the file and waits for the user to press F1 to quit.
Display file (approximation):
A R DISPLAY
A CA01(01 'Exit')
A 2 2'some text....'
Creation command: crtdspf file(display) srcfile(test) srcmbr(display)
CL program:
PGM
DCLF FILE(DISPLAY) RCDFMT(DISPLAY)
LOOP: SNDRCVF
IF COND(&IN01 *EQ '1') THEN(DO)
GOTO END
ENDDO
GOTO LOOP
END:
ENDPGM
Compile command: crtclpgm pgm(test) srcfile(test) srcmbr(clsrc) output(*print)
What is the equivalent of SNDRCVF in C?
Here is what I've come with so far. It compiles fine, but when I call it, it does nothing.
#include <stdio.h>
#include <recio.h>
// Include my display file.
#pragma mapinc("display","lib/display(display)", "both", "")
#include "display"
// Shortcuts to the generated structs.
typedef LIB_DISPLAY_DISPLAY_i_t input_t;
typedef LIB_DISPLAY_DISPLAY_o_t output_t;
int main(int argc, char* argv[]){
input_t input;
output_t output;
_RFILE* dspf;
// The file opens fine.
dspf = _Ropen("lib/display", "wr");
if(dspf == NULL){
printf("ERROR: Display file open failed.\n");
return 0;
}
// I tell which record format to use.
_Rformat(dspf, "display");
// Write my file to display?
_Rwrite(dspf, "", 0);
// Wait for input.
_Rreadn(dspf, &input, sizeof(input), __DFT);
// Close it and quit.
_Rclose(dspf);
return 0;
}
Compile command: crtbndc pgm(test) srcfile(test) srcmbr(main) output(*print)
Then call: call test
What am I doing wrong?
I made a few minor changes. First, for your TYPEDEFs, I used this:
// Shortcuts to the generated structs.
typedef MYLIB_CDSPMNU_DISPLAY_both_t input_t;
typedef MYLIB_CDSPMNU_DISPLAY_both_t output_t;
Because you specified "both", the referenced identifier name should have 'both' rather than 'i' or 'o'. It's not clear how you could've successfully compiled as you had it. Perhaps you had an earlier successful compilation so that your CALL command worked, but the compiled program wasn't a current version.
Then I opened the file with this mode:
// The file opens fine.
dspf = _Ropen("mylib/cdspmnu", "rr+");
You had "wr", so it it was opened only for output ("wr"iting). You need it for input and output. Your joblog should show a C2M3005 "File is not opened for read operations." after you CALL your program (depending on what compiled version you actually CALL).
And I changed your _Rformat() function:
// I tell which record format to use.
_Rformat(dspf, "DISPLAY");
From the ILE C/C++ Runtime Library Functions manual, the definition of _Rformat() says:
The fmt parameter is a null-ended C string. The fmt parameter must
be in uppercase.
The format name isn't folded to uppercase like file and library names are in other places. No idea why not; it's just the way it is. Personally, I'd use uppercase wherever it actually means an uppercase name without relying on the compiler; so I'd also change a couple other places in the code.
Technically, I also changed the DSPF source to reference the F3 key rather than the F1 key that you show in your DDS. The F1 key would normally be for 'help' functions while F3 is a standard for 'Exit'. That doesn't really matter, but it's one habit to get started. And a name or two was changed just to fit within my environment.
No spooled files were necessary. Easiest way to view your job's "joblog" after a CALL command is to run a DSPJOBLOG command. Perhaps better, though, is to use the basic command entry display provided by CALL QCMD. Basic joblog messages can be toggled on/off on that display by use of the F10 key to either "Include detailed messages" or "Exclude detailed messages".
All in all, you were pretty close. Not bad at all if this was your first attempt to work with a DSPF.

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.

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