Debugging in c for log file - c

I have written down a program in c and I am trying to create a log file of it.
The problem I am facing is that while printing the outputs of each line in the file I want to write some distinctive feature such as the time of execution of that line or even the line number in the code.
Is there any way I can get to know any of these two.
I don't mind if you suggest some other way to get a distinctive feature. All I want is that looking at the log file the user gets to know that a certain part of the code was getting executed.
Thanks
I am working on linux and thus using the GCC compiler....
I have made a header file and in it I am for testing purposes writing __LINE__ . What I want to do is that in a program when I include this function of header file the line number gets printed where the function is. But instead i get the line number of the header file printf statement.
What do I need to do to get the line number of the file .
This is just a test format given below :-
new.h
void print()
{
printf("Line number is %d",__LINE__);
}
actual file
#include "new.h"
int main()
{
print();
}
Then I want that the line number that should be printed is that of actual file and not new.h which happens now....

Most C compilers provide some macros to identify each line, function, etc. With GCC, for example, you can use __LINE__, __FUNCTION__, and so on. Check your compiler documentation for details. To get a timestamp, you'll need to let us know what system you're working on.

If you want the actual date and time the function was executed, try asctime(). There is a good reference on how it's done here.
This will output something akin to Sat May 20 17:36:17 2000. If you want the time in seconds since the program started, have a variable such as int startTime = time() which holds the program start time in seconds from the Unix Epoch. Then, simply print startTime - time() to get the number of seconds since program start.

In GCC you can get line number as "__LINE__". Filename - "__FILE__".
If you want calculate execution time then just remember time on start, get time on end and substract them.

The line number can be obtained by the preprocessor macro __LINE__. The file is __FILE__. As for time, use the relevant OS library.
Or, use a logging library that support these.

Use __FILE__ and __LINE__ to get the current file and line number.
Edit: based on your edited question. Here's a simple way to do it to start.
new.h
#define PRINT() print(__LINE__)
void print(int line)
{
printf("Line number is %d",line);
}
actual file
#include "new.h"
int main()
{
PRINT();
}

Related

Rebound: fatal error while opening a file

I am using a software called Rebound which is a type of N-body integrator that generates simulations according to a certain code I wrote. the software uses built in functions of its own which are based on C.
part of the code I wrote is when I'm telling the program to output certain data into separate text files every set period of time.
char array [1000000];
if (reb_output_check(r, 49.581410)){
sprintf(array, "output%d.txt", i);
i++;
reb_output_orbits(r, array ); //output the orbital elements
}
the reb_output_check function checks whenever the time is a multiple of 49.581410 years in simulation r to execute the rest.
everything is working out fine until the 252nd output where the simulation stops and this appears:
Fatal error! Exiting now. Can not open file
I've repeated the simulation more than once and I'm getting the same thing at the same time every time. I don't know why it's giving me this.
any help regarding the matter is much appreciated.

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.

multiple definition of main first defined here

I'm new to programming and currently I'm learning C programming. I'm writing codes on the code blocks and in it using GCC compiler. When I create a new project, (as you know it creates main.c file with it) and due to that I'm not able to compile another file in that project.
File 1:
#include<stdio.h>
int main()
{
int a,b,c,d;
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
d=a;
if(b>d)
d=b;
if(c>d)
d=c;
printf("\n The maximum of three numbers is %d",d);
}
File 2: main.c
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}
When I compile the first programme, it shows the following error:
multiple definition of 'main'
first defined here
I've searched every where I could and I'm not able to solve this. In one of the answers here on stack overflow, someone had suggested to write this in
(Project->Build options...->Linker settings (tab))
-Wl,--allow-multiple-definition
When I wrote it, there were no errors. But it wasn't able to run my File 1 and instead, it runs that main.c file. Even when I close the main.c file, it opens there again and runs main.c file which gives the output "Hello World!".
Initially when I was using code blocks there were no such errors. I don't know why this is happening and I've not much knowledge about compilers.
As noted in comments you can only have one main function.
So when you start a new project you need to replace the main.c file with the main.c file you want to use. Or you can edit the 'hello world' main.c program.
When you start a new project in code::blocks you can get a new directory with a simple program that prints 'Hello World'. This file is usually main.c. You need to edit this file or replace it. The reason that code::blocks puts this simple main.c program in the new project is so that you can compile it and test your system without having to write a new program.
Some computer languages allow you to use the same function name for different functions ( which are identified by their parameters and sometimes return types ). That's called overloading. C does not allow this. Functions in C must have unique names.
The main() function is a special one in C as it is used as the standard entry point for applications. That is, the main() function will be called first and your application should start and (typically) end in that function.
As a beginner I would suggest you avoid automated editor features that create and build projects for you. You will miss out on learning how things work doing that. Use an editor to start from empty files and learn how they all connect and how to use the compiler from the command line. The command line is something every beginner should start from, IMO.
It may be harder to learn, but it will give you a much better feel for what is going on.
I guess what you maybe trying to do is have multiple sandbox "gists" that you may wanna run all as their own main function. If that is the case, then just close your project and open the files directly. As long as they are not in a project, they will run fine.

C/C++ BEGINNER - fgets with stdin causing unexpected 'loop' results

I'm a programming student who's only really looked at Java up until now. This semester is our first time using C and I'm having a lot of trouble wrapping my head around some of the simplest functions. I really have no idea what I'm doing. I couldn't even get Eclipse to work correctly with MinGW so I eventually gave up and reverted to Netbeans.
So basically I'm trying to use fgets to read user input for a switch-case menu, but I can't get fgets to work in even the simplest situations. To troubleshoot I tried copying a simple fgets example from online, but even that is giving me unexpected results.
When I run the code below it just runs an infinite empty loop (it does not prompt for user entry at all, it does not accept any user entry, it just 'runs' forever and the console remains blank). When I delete the fgets line and remove the other reference to the 'name' variable it works as you would expect (prints the user entry prompt and then ends).
Example code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
return (EXIT_SUCCESS);
}
Any advice would be appreciated!
Other info:
I am running - Win 8 (poor me) & Netbeans IDE 8.0 (with MinGW)
When creating my C project I select File=> New Project=> C/C++=> C/C++ Application
EDIT: When I run the program I have tried:
1) right clicking the project file => Run; and
2) clicking the big green arrow in the netbeans ribbon;
.... neither works.
This code should work, but for you to be able to input anything, you need to run in in a proper terminal.
My guess is that you're running it inside your IDE and it's set to use pipes as stdin/stdout. Instead you should start cmd.exe and run the program in there (you'll have to navigate to the correct directory first).
Or, optionally, there might be a setting in your IDE to run the program using cmd.exe or with a builtin terminal.
A final note. You should learn to use sizeof whenever a buffer size is required. I.e. change this:
fgets(name,10,stdin);
to
fgets(name, sizeof(name), stdin);
Also, please use spaces to make your code more readable. Reading code is a big part of programming.
1) You might want to flush the file, after printf("Who are you? "); with fflush(stdout);
2) You have two return statements (which is harmless).
Other than that, your code is fine.
It works perfect - but you might want using fflush(stdin); before the fgets() call.
Also remember fgets return a string with '\n' after a user input - solved simply with name[strlen(name)-1]='\0'; - which is basically putting NULL as an "end of a string" symbol, basically you remove the '\n'.
And DO NOT change 10 to sizeof(name) - it doesn't matter at all, basically it's even supposedly worse as you can't use this in functions properly (sizeof(name) won't always match the length and would be the size of the pointer).
You should try compiling with MinGW if it didn't work, it will surely work on it.
A reminder: fgets() may let you enter MILLION characters, but it will take the first 10, in this case, at least.

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Resources