I believe my issue stems from the printf print buffer, but I know too little about C or buffers to know how to handle this. I have a simple program written and it just prints a bunch of text (chars/strings) based on some if/else statements depending on the file that is input. If I call it from a Unix shell like so:
gcc -o myProgram myProgram.c
./myProgram fileName
It will print out correctly for only the first run. If i reiterate these steps and once again run the program, it prints out a bunch of “bash” commands in between the output printfs. Is there an easy way to debug or fix this issue? I’m very new to C, if you couldn’t tell, and I’m using this as part of a school assignment so I am trying to actually figure this out and understand this concept, such that I can then apply it back into my actual program assignment.
EDIT: This is a make-shift example to try to demo my issue
Note: The file inputted just contains text.
#include <stdio.h>
#include <stdlib.h>
struct S{
char word[30];
}s;
int main(int argc, char ** argv)
{
void print(struct S *s);
int i;
FILE *f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_SET);
fread(&s, sizeof(s), 1, f);
print(&s);
fclose(f);
}
void print(struct S *s)
{
int i = 0;
printf("Word: ");
for(i = 0; i < 30; i++)
{
if(s->word[i] != '\0')
{
printf("%c", s->word[i]);
}
else
{
break;
}
}
printf("\n");
}
You can test this :
Add the following line at the first line in the main() :
The outputs of a program are stored in a buffer and when you call printf they are extracted. the setbuf() method is used for handling that buffer. when You add setbuf(stdout , NULL), this tells the buffer that don’t store the outputs and directly send outputs of the program into the stdout.