Why can't I printf() to stdout in C without using fflush()? - c

I recently started programming in C and something I can't seem to get my head around is the way stdout prints to screen.
When I added all my statements in the main() function and used the printf() function everything worked well, all the printf() statements were able to print to stdout.
From Main.c
...
#include "HeaderFile.h"
int main(int argc, char * argv[]){
...
printf("%c\n", testChar);
return 0;/*End of execution. Returns 0 value and ends gracefully*/
}
...
But when I started to modularize my code in different functions, I realised that I have to insert the fflush(stdout) function at the end of each printf() function in order for the print function to print out to stdout:
From ReadFile.c
...
#include "HeaderFile.h"
void readFileFunction(char* file){
...
printf("%c\n", testChar);
fflush(stdout);
...
}
...
Header file:
/*This is the header file used by the Linked list program.*/
/*This is the header file used by the Linked list program.*/
#ifndef HEADERFILE_H /* Include guard */
#define HEADERFILE_H
#include <stdio.h> /*including the stdio file inside the Main.c file. stdio.h is a header file, where this and other similar functions are defined.*/
#include <string.h>/*including the string file inside the Main.c file. string.h is a header file, where this and other similar functions are defined.*/
#include <time.h>/*including the time file inside the Main.c file. time.h is a header file, where this and other similar functions are defined.*/
#include <stdint.h>/*including the stdint file inside the Main.c file. stdint.h is a header file, where this and other similar functions are defined.*/
#include <stdlib.h>/*including the stdlib file inside the Main.c file. stdlib.h is a header file, where this and other similar functions are defined.*/
#include <errno.h> /*including the errno file inside the Main.c file. errno.h is a header file, where this and other similar functions are defined.*/
#include <regex.h>
extern const char errorString[]; /*A string of characters. Indicates an error message when the program in-counters a problem during execution.*/
/*String constants used to match user input with a specific function.*/
extern const char *string1;
extern const char *string2;
extern const char *string3;
extern const char *string4;
extern const char *string5;
extern const char *string6;
extern const char *string7;
extern const char *string8;
extern const char *string9;
/*Node structure with character value and the next node.*/
typedef struct node {
char value;
char type;
struct node * next;
} nodeStruct;
/*function prototypes for every function being used in the code.*/
int removeChar(nodeStruct ** head, char value);
void readFileInit(char* file);
void readFileFunction(char *file);
void printList(nodeStruct * head) ;
void push(nodeStruct ** head, char value) ;
char tail(nodeStruct * head) ;
char head(nodeStruct * head) ;
int length(nodeStruct * head) ;
int pop(nodeStruct ** head) ;
int regularExpr (const char *patt, char *str) ;
void append(nodeStruct ** head, char value) ;
int insertAfter(nodeStruct ** head, char value, char value2) ;
int insertBefore(nodeStruct ** head, char value, char value2) ;
#endif // HEADERFILE_H
Would you please explain in details why this sudden difference?

The function prototype for fflush is this:
int fflush ( FILE * stream );
It flushes the file pointer to the stream ensuring its written.
Depending on the environment where the code is executing on, the stdout in this case could well be buffered, implying that it does not get written straight away. fflush alleviates that and ensures it is flushed out.
Another thing, the kernel could be under a load at the point of execution thus delaying the printing to the console or terminal in this case, in which case, ending up judiciously sprinkling fflush all over the place.
It might help to enclose a SCCE example as looking at the OP's question, it is not easy to discriminate as to why, more of rather what is happening.
Edit:
The code can specify that the output is automatically written without buffering by including this snippet
setbuf(stdout, NULL);
It would be good practice, to save the state of buffer control at the start, switch off the buffering, and at end of code execution restore the buffer control.

Related

Passing struct pointer as a parameter

I'm trying to compile this code in c. First of all i have this struct in a separate source file to use it like a "class" (dir.h)
//Structure
typedef struct s_dirobject {
int noteid;
char title[20];
int bytes;
char head[20];
bool is_dir;
struct s_dirobject* next;
} dirobject;
//Ops
void add_dirobject(dirobject* myDirobject,int num_dirobject, char title[20], int is_dir, int bytes, char head[20]);
int get_dirobject_noteid(dirobject* myDirobject,int num_note);
char* get_dirobject_title(dirobject* myDirobject,int num_note);
int get_dirobject_bytes(dirobject* myDirobject,int num_note);
char* get_dirobject_head(dirobject* myDirobject,int num_note);
bool isdir(dirobject* myDirobject, int num_note);
int get_dirobjects_len(dirobject* myDirobject);
void clear_dir(dirobject* myDirobject);
void init_dir(dirobject* myDirobject);
In second place i have the comms source to retrieve the contents of a directory from a remote file system, and fill the object (comms.c)
#include "notebook.h"
#include "dir.h"
dirobject* temporaldirobjects;
...
init_dir(temporaldirobjects);
while(cond) {
//Add retrieved item to the directory
add_dirobject(temporaldirobjects, index, title, is_dir, bytes, "");
}
//When done retrieving the contents from the source i do instantiate the notebook_window
notebook_init(source, path, temporaldirobjects);
Finally, my notebook window interface will look like this. (notebook.h)
#include "dir.h"
void notebook_init(char* source, char* path, dirobject* contents);
void notebook_deinit();
And its implementation (notebook.c)
void notebook_init(char* source, char* path, dirobject* contents) {
// Fill the vars
this_window_source=source;
this_window_path=path;
this_window_dirobjects=contents;
...
}
When i compile this code as is, i get the error saying that
../src/dir.h:13:16: error: redefinition of 'struct s_dirobject'
In file included from ../src/notebook.h:12:0,
from ../src/comms.c:25:
../src/dir.h:13:16: note: originally defined here
In file included from ../src/comms.c:27:0:
../src/dir.h:20:3: error: conflicting types for 'dirobject'
In file included from ../src/notebook.h:12:0,
from ../src/comms.c:25:
../src/dir.h:20:3: note: previous declaration of 'dirobject' was here
In file included from ../src/comms.c:27:0:
../src/dir.h:23:6: error: conflicting types for 'add_dirobject'
In file included from ../src/notebook.h:12:0,
from ../src/comms.c:25:
../src/dir.h:23:6: note: previous declaration of 'add_dirobject' was here
...
since the comms library includes dir.h and notebook.h, and notebook.h does it too.
and if i remove the include in notebook.h i got this other error:
In file included from ../src/comms.c:25:0:
../src/notebook.h:14:46: error: unknown type name 'dirobject'
How can i acheive this? I would like to keep it as clean code as i can.
You included two headers in file comms.c
#include "notebook.h"
#include "dir.h"
header notebook.h in turn includes header dir.h
#include "dir.h"
void notebook_init(char* source, char* path, dirobject* contents);
void notebook_deinit();
As result the structure is defined twice in the same compilation unit. You have to provide that each headers would be included only once in each compilation unit. To do this you have to supply header's quards. For example
#ifndef DIR_H
#define DIR_H
//Structure
typedef struct s_dirobject {
int noteid;
char title[20];
int bytes;
char head[20];
bool is_dir;
struct s_dirobject* next;
} dirobject;
//...
#endif
Or if the compiler supports #pragme once then you could use it.
Usually, multiple declarations are fine in c but multiple definition is not. In your code, you are including dir.h multiple times which is causing the redefinition of struct s_dirobject. Read something about "Header guard" or "Include Guard". here. Hope this solves your major issues with redefinitions.

Multiple definition error upon including headers( How to add header in c?)

I have such project, which includes 1.c 2.c and mygost.h files.
//mygost.h looks this way
#ifndef MYGOST_H_
#define MYGOST_H_
#include <stdint.h>
uint8_t transl_table(uint8_t in, uint8_t n) {
return tbl[n][in];
}
const char *get_filename_ext(const char *filename)
{
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
#endif
//1.c
#include <malloc.h>
#include "mygost.h"
// here we call defined before functions
//2.c
#include <malloc.h>
#include "mygost.h"
// here we call defined before functions
If I include this header only in one .c file, everything will be fine. Otherwise I get Multiple definition error of const char *get_filename_ext(const char *filename) function and all other function in the header. In addition, I dont redefine these functions in a code at all. Don`t know how to fix this.
I use QNX Momentics Tool Suite, which has own compliler (http://www.qnx.com/products/tools/qnx-momentics.html), but it works like gcc as far as I know.
UPD1: Compiler gives such errors
Severity and Description Path Resource Location
2.c: multiple definition of `get_filename_ext' GostQnx line 0
..........
make[2]:***[C:/ide-4.5-workspace/GostQnx/x86/o-g/GostQnx_g] Error1 GostQnx line 0
make[2]:***[C:/ide-4.5-workspace/GostQnx/x86/o/GostQnx] Error1 GostQnx line 0
first defined here GostQnx mygost.h line 16
................
multiple definition of `get_filename_ext'GostQnx mygost.h line 151
..........
UPD2: adding static or inline don`t effect.
You should not define a function in a .h file. The error is most likely the missing function prototype const char *get_filename_ext(const char *);
(edited following comment)
//mygost.h looks this way
#ifndef MYGOST_H_
#define MYGOST_H_
#include <stdint.h>
extern uint8_t transl_table(uint8_t in, uint8_t n);
extern const char *get_filename_ext(const char *filename);
#endif
//mygost.c looks this way
#include "mygost.h"
extern uint8_t transl_table(uint8_t in, uint8_t n) {
return tbl[n][in];
}
extern const char *get_filename_ext(const char *filename)
{
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
When you include in 1.c, the compiler declares the function and make an assumption on it's prototype since it is not defined. And does the same the second time it is included in 2.c. The usual way would be to declare a function prototype in mygosh.h, and put the actual function declaration in a mygosh.c containing the implementation details.
Bear in mind that I only rewrote according to your example (for example I did not correct the undeclared variable in trans1_table)
Having the full output from the compiler would help to be more precise. As the compiler and platform (ex: gcc 4.7 under ubuntu 12.04).
Also, I tried to compile your code under fedora 19 with gcc 4.7 and it does not compile because of some unknown types that are either defined elsewhere in your real project or because it could also be a cause of your problem. Try to rewrite as a self contained compilable example. If you want, you can check a gitorious project I started out a while ago for another stack overflow question you can look at for ideas.
https://gitorious.org/c-cli-rubix-cube

How should I organize this C project

I am doing this programming assignment in C. But I am confused as to how to organize it.
So, here is the situation. I have two tree implementations and declare their struct/includes/function prototypes and so on in two separate header files. Then I have two c source code for the two implementations. Now here comes the problem. I have one test c file (only one main function for running tests) for the ADTs of Trees. Since the two implementations are going to use the same test. How can I avoid making two copies of the same main.c file? when I include the header file of tree implementation1, I can do gcc Tree_implementation1.c main.c. But to do implementation2, I have to got back in the main source file and manually change the include to tree implementation2, and then I can use the same compilation command. How do I work around this to toggle between the two implementations with only one main.c?
Use the preprocessor and a constant that you can set on the command line:
In your main.c:
#ifdef TREE_IMPL1
#include "TreeImplementation1.h"
#else
#include "TreeImplementation2.h"
#endif
// ...
int main(int argc, char **argv)
{
#ifdef TREE_IMPL1
// code for testing TreeImplementation1
#else
// code for testing TreeImplementation2
#endif
}
When you compile, pass or omit TREE_IMPL1 on the command line, or set it in your IDE:
gcc -DTREE_IMPL1 main.c ...
Do your implementations have the same name? They shouldn't.
If (or when) they don't have the same name, you can just include both headers in main.c and test either one depending on some preprocessor directive.
//main.c
#include "Tree_implementation1.h"
#include "Tree_implementation2.h"
int main()
{
#ifdef TEST_FIRST
testFirstTree(); //declared in Tree_implementation1.h
#else
testSecondTree(); //declared in Tree_implementation2.h
#endif
return 0;
}
Another solution for your problem is using of dynamic interface.
Work the way like that:
#include "Imp_1.h"
#include "Imp_2.h"
typedef void (*TreeFunctionType1)(Tree,param);
typedef void (*TreeFunctionType2)(Tree);
typedef struct ITree
{
TreeFunctionType1 func1;
TreeFunctionType2 func2;
}ITree;
static ITree _Itree={0};
void SetImp(TreeFunctionType1 f1,TreeFunctionType2 f2)
{
tree.func1 = f1;
tree.func2 = f2;
}
/*Use only this functions in your Tests code*/
//{
void Func1(Tree tree,Param param)
{
(*_Itree.func1)(tree,param);
}
void Func2(Tree tree)
{
(*_Itree.func2)(tree);
}
//}
int main(int argc, char const *argv[])
{
SetImp(Imp_1_f1,Imp_1_f2);
TestCode();
SetImp(Imp_2_f1,Imp_2_f2);
TestCode();
return 0;
}

#including files [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I got a problem with including files.
What I've basically made is a command-line program in C that works with a csv file. It has 5 commands: -menu, -add, -edit, -del, -verify. All is good except for the -menu. What needs to happen when I type "./passweb -menu" is for a visual menu to appear. This menu command should call a new function and it needs to be located in a separate c file (aka menu.c).
The problem I'm having right now is that I'm not too sure how to include the files to run in the menu.c because the way I have it set up right now, passweb.c has all the functions such as -add and -edit and etc. I know you need to make header files and such but it's complaining that I've declared the methods twice which is true since I use the functions in the menu file.
Here's some of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cipher.h"
#include "menu.h"
#include "passweb.h"
#define MAXLENGTH 51 //longest length of a single record + 1 =51 bytes
#define SIZEOFDB 1000
#define ENCRYPT 5
typedef struct rec
{
char name[MAXLENGTH];
char pw[MAXLENGTH];
char type[6];
int boolean;
}RECORD;
int add(char *nName, char *nPw, char *nType, RECORD *arr, int size);
void del (char *tName, RECORD *arr, int size);
int edit(char *nName, char *nPw, char *nType, char *tName, char *tPw, RECORD *arr, int size);
int verify (char *tName, char *tPw, RECORD *arr,int size);
This is my main file "passweb.c" and it's declared the functions.
Later on in the main, I will call a menu function which is located in a menu.c file.
In the menu function I use "add","edit","del" and etc that I wrote in this .c file.
As you can see on the top, I have included the header files.
What can I do to solve this problem?
Sorry for the long post.
Thanks
You should put function prototype in the header file. You should put its implementation in the source file, which should include the header file.
For example, the header (test.h) would have the structure definitions and function prototypes like:
#ifndef TEST_H
#define TEST_H
struct myStruct {
int x;
};
int Add(int lhs, int rhs);
#endif
And the source would have:
#include "test.h"
#include <stdio.h>
int Add(int lhs, int rhs)
{
return lhs+rhs;
}
int main()
{
printf("%d",Add(2,3));
return 0;
}
put this in your header file and include it:
#ifndef FUNCS_H_
#define FUNCS_H_
int add(char *nName, char *nPw, char *nType, RECORD *arr, int size);
void del (char *tName, RECORD *arr, int size);
int edit(char *nName, char *nPw, char *nType, char *tName, char *tPw, RECORD *arr, int size);
int verify (char *tName, char *tPw, RECORD *arr,int size);
#endif /*FUNCS_H_*/
the #ifdef guards the header from multiple inclusion
Move the declaration of add, del, edit and verify in a new include file main.h
Include main.h in your main .c file and in menu.c
In general is also a good idea to put directives in the include files that tells the preprocessor to use them only once - Visual C++ has a special #pragma once directive for that, otherwise you can use
#if ! __MENU_C
#define __MENU_C
. . . .
#endif
The header file should contain your function prototypes and the necessary information about the data types they reference, such as your struct definitions. It may also include #define'ed constants, inline functions, declarations of extern variables (which would be declared normally inside one of your .c files), etc.
Once you have these things in your header file, you can remove them from the .c file(s); the actual function definitions, with the bodies, should be in the .c files -- but don't duplicate the prototypes there. You then #include the header in each .c file that needs the functions, etc. declared in it.
You also need to ensure that the items in the header file don't get #include'ed more than once in each source file, even indirectly (included from another include). Usually header guards are used for this, which use preprocessor conditionals to prevent processing of the header file when it has already been included:
#ifndef SOMEHEADER_H
# define SOMEHEADER_H
/* header file contents */
#endif
When compiling, you should be able to compile each .c file separately if you like, or all together if the compiler lets you. When linking, you need to link all the object files though. For gcc, doing both in one command, you might use something like this:
gcc -o program_name first.c second.c third.c
...which compiles each .c file to its own .o file, and links all of them together when producing the executable.

undefined C struct forward declaration

I have a header file port.h, port.c, and my main.c
I get the following error: 'ports' uses undefined struct 'port_t'
I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.
I need to have the forward declaration as I want to hide some data in my port.c file.
In my port.h I have the following:
/* port.h */
struct port_t;
port.c:
/* port.c */
#include "port.h"
struct port_t
{
unsigned int port_id;
char name;
};
main.c:
/* main.c */
#include <stdio.h>
#include "port.h"
int main(void)
{
struct port_t ports;
return 0;
}
Many thanks for any suggestions,
Unfortunately, the compiler needs to know the size of port_t (in bytes) while compiling main.c, so you need the full type definition in the header file.
If you want to hide the internal data of the port_t structure you can use a technique like how the standard library handles FILE objects. Client code only deals with FILE* items, so they do not need (indeed, then generally can't) have any knowlege of what is actually in the FILE structure. The drawback to this method is that the client code can't simply declare a variable to be of that type - they can only have pointers to it, so the object needs to be created and destroyed using some API, and all uses of the object have to be through some API.
The advantage to this is that you have a nice clean interface to how port_t objects must be used, and lets you keep private things private (non-private things need getter/setter functions for the client to access them).
Just like how FILE I/O is handled in the C library.
A common solution that I use:
/* port.h */
typedef struct port_t *port_p;
/* port.c */
#include "port.h"
struct port_t
{
unsigned int port_id;
char name;
};
You use the port_p in function interfaces.
You will need to create special malloc (and free) wrappers in port.h as well:
port_p portAlloc(/*perhaps some initialisation args */);
portFree(port_p);
I would recommend a different way:
/* port.h */
#ifndef _PORT_H
#define _PORT_H
typedef struct /* Define the struct in the header */
{
unsigned int port_id;
char name;
}port_t;
void store_port_t(port_t);/*Prototype*/
#endif
/* port.c */
#include "port.h"
static port_t my_hidden_port; /* Here you can hide whatever you want */
void store_port_t(port_t hide_this)
{
my_hidden_port = hide_this;
}
/* main.c */
#include <stdio.h>
#include "port.h"
int main(void)
{
struct port_t ports;
/* Hide the data with next function*/
store_port_t(ports);
return 0;
}
It is generally no good to define variables in a header file.

Resources