fflush(stdout) not working but \n' works in C language - c

I was working on a homework problem when I encounter this error, fflush inside main function in main.c is not working
I tried the code in ubuntu local system and in repl.it and the output does not contain "#include" line from sample.c , The only line "preprocessor " is printed in terminal..
Files used:
main.c
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
char token[1024];
int toksize = 0;
int breaker = 0;
int is_normal(char ch) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| ch == '_' || (ch >= '0' && ch <= '9'))
return 1;
return 0;
}
int Tokenizer(FILE * file_ptr) {
char ch;
toksize = 0;
ch = 'a';
while (is_normal(ch) == 1 && ch != EOF) {
ch = fgetc(file_ptr);
if (ch == EOF) break;
if (toksize > 0 && !is_normal(ch)) break;
token[toksize] = ch;
toksize++;
token[toksize] = '\0';
}
if (ch == EOF)
breaker = 1;
if (toksize > 1 || is_normal(token[0]))
fseek(file_ptr, -1L, SEEK_CUR);
// fflush(stdin);
// fflush(stdout);
return 1;
}
int main() {
fprintf(stderr, "ji");
int flag = 0;
FILE * fd = fopen("sample.c", "r");
breaker = 0;
if (fd == NULL) {
printf("file not found!!");
return 0;
}
while (breaker == 0 && Tokenizer(fd) > 0) {
int stage = 0;
if (token[0] == '#') { // handling preprocessor
while (token[0] != '\n') {
printf("%s", token);
if (Tokenizer(fd) == 0) {
breaker = 1;
break;
}
}
fflush(stdout);
printf(" -- preprocessor directive\n");
}
}
}
sample.c
#include<stdio.h>

Related

how do I read non .txt file in c programming?

I want to read a c file from another c program.
and print it line by line.
But I got some problem.
here is my code, the file to be read and the output i'm getting in terminal.
my Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sourcefilename[100];
char targetfilename[100];
int counter = 0;
int lower_limit = 10;
char *line = NULL;
char *temp = NULL;
int is_multilinecomment = 0;
FILE *source = fopen("hello.c", "r");
FILE *target = fopen("newcode.c", "w");
char ch = fgetc(source);
while (ch != EOF)
{
// printf("%c", ch);
if (ch == '\n')
{
counter = 0;
printf("%s\n", line);
free(line);
line = NULL;
}
else
{
temp = (char *)realloc(line, counter * sizeof(char));
if (!temp)
{
free(line);
line = NULL;
}
line = temp;
line[counter] = ch;
counter++;
// printf("%s", line);
}
// printf("helo");
ch = fgetc(source);
}
return 0;
}
hello.c
I'm trying to read this file
#include <stdio.h>
#include <string.h>
// this is a single line comment
int main()
{
char var[500];
printf("Enter a name of a variable : ");
scanf("%s", var);
if (!((var[0] >= 'a' && var[0] <= 'z') || (var[0] >= 'A' && var[0] <= 'Z') || var[0] == '_'))
{
printf("%s is not valid variable.\n", var);
return 0;
}
// this is another single line comment
for (int i = 1; i < strlen(var); i++)
{
if (!((var[i] >= 'a' && var[i] <= 'z') || (var[i] >= 'A' && var[i] <= 'Z') || var[i] == '_' || (var[i] >= '0' && var[i] <= '9')))
{
printf("%s is not valid variable.\n", var);
return 0;
}
}
/*
this is a multi line
comment */
printf("%s is valid variable.\n", var);
return 0;
}
output i'm getting
#include <stdio.h>\Progr�
#include <string.h>
// this is a single line comment`�
int main()�
{�
char var[500];e line/
printf("Enter a name of a variable : ");{~
scanf("%s", var);ame/
if (!((var[0] >= 'a' && var[0] <= 'z') || (var[0] >= 'A' && var[0] <= 'Z') || var[0] == '_'))�
{
printf("%s is not valid variable.\n", var);
return 0;s is nok�_z~
}
// this is another single line comment
for (int i = 1; i < strlen(var); i++)
{
if (!((var[i] >= 'a' && var[i] <= 'z') || (var[i] >= 'A' && var[i] <= 'Z') || var[i] == '_' || (var[i] >= '0' && var[i] <= '9')))
_�
you can notice here i'm getting some unwanted characters at the end of each line.
and also last part of the hello.c is ignored.
please help !!!
You have multiple issues in your code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sourcefilename[100];
char targetfilename[100];
int counter = 0;
int lower_limit = 10;
char *line = NULL;
char *temp = NULL;
int is_multilinecomment = 0;
FILE *source = fopen("hello.c", "r");
FILE *target = fopen("newcode.c", "w");
char ch = fgetc(source);
Function fgetc returns an int. This is required to detect EOF. Do not use char.
while (ch != EOF)
See Why is “while ( !feof (file) )” always wrong? for details
{
// printf("%c", ch);
if (ch == '\n')
{
counter = 0;
printf("%s\n", line);
If you hit an empty line, you do not have any memory allocated for line and it contains NULL, causing undefined behaviour.
In any case you do not have a terminating 0 byte in your line buffer. This means it is not a valid string and passing that character array to printf again causes undefined behaviour.
free(line);
line = NULL;
}
else
{
temp = (char *)realloc(line, counter * sizeof(char));
You start with counter=0 for each line. You allocate 0 bytes for first character. Instead of allocating memory for your string + 1 byte for terminating \0 byte, you allocate 2 bytes less.
if (!temp)
{
free(line);
line = NULL;
}
line = temp;
line[counter] = ch;
If condition (!temp) was true above, you still assign temp to line and dereference it, causing undefined behaviour.
counter++;
// printf("%s", line);
}
// printf("helo");
ch = fgetc(source);
}
return 0;
}
Some more issues, not related with weird characters:
You do not write your output to target file.
You do not close your files.
A proper signature for main should be int main (void). Empty parameter list in function definition should not be used nowadays.
Most of your variables in main are unused.
Not all included headers are actually required.

The use of strlen on calculating the size of a string

I need to calculate the size of a string in order to apply a function (the function applied is going to depend on the size of valor.)
However, as you can see in this example, I am having some trouble using strlen in the string (in the example you can see I inserted 2 'valor' and the given strlen was 6).
Here is the code, and next to it an image of the process returned.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char valor[5];
char naipe[5];
int c;
int i = 0;
do {
c = getchar();
if (((c > '0') && (c < '9')) || (c == 'K') || (c == 'Q') || (c == 'J') ||
(c == 'A') || (c == 'T')) {
valor[i] = c;
continue;
}
if ((c > 'A') && (c < 'Z')) {
naipe[i] = c;
i++;
}
} while (c != '\n');
printf("%ld", strlen(valor));
return 0;
}
you have two arrays and you should use two counters for them ,otherwise you would probably skip some elements of each arrays.
also you should terminate char valor[5] and char naipe[5] with '\0'.
int main() {
char valor[5];
char naipe[5];
int c;
int i = 0,j=0;
do {
c = getchar();
if (((c > '0') && (c < '9')) || (c == 'K') || (c == 'Q') || (c == 'J') ||
(c == 'A') || (c == 'T')) {
valor[j] = c;
j++;
continue;
}
if ((c > 'A') && (c < 'Z')) {
naipe[i] = c;
i++;
}
} while (c != '\n');
valor[j] = '\0';//terminate first then print.
printf("%ld", strlen(valor));
naipe[i] = '\0';
return 0;
}

Program to count lines, char, or words from file

I am writing a program to count words as practice but I am running into a problem where it is incorrectly counting no matter which option I choose.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(int argc, char **argv){
int totalcount = 0; //hold overall count
for(int i = 2; i < argc; i++){
int count = 0; //hold count for each file
int c; //temporarily hold char from file
FILE *file = fopen(argv[i], "r");
if (strcmp("-c",argv[1])){
while((c = fgetc(file)) != EOF){
count++;
}
}
else if(strcmp("-w",argv[1])){
bool toggle = false; //keeps track whether the next space or line indicates a word
while((c = fgetc(file)) != EOF){
if(!toggle && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))){
toggle = true;
}
if(toggle && ((c == '\n') || (c == ' '))){
count++;
toggle = false;
}
}
}
else{
while((c = fgetc(file)) != EOF){
if(c == '\n'){
count++;
}
}
}
printf("%d %s", count, argv[i]);
fclose(file);
totalcount += count;
}
if (argc > 3){
printf("%d total", totalcount);
}
return 0;
}
I don't know why my logic for char count doesn't work. I have ran through my logic when writing each section and it doesnt make sense to me why it would not me working. Any help would be greatly appreciated.
strcmp returns 0 when the strings equal, so never enter into the if/else statement
if (strcmp("-c",argv[1]) == 0){ //return value is 0
while((c = fgetc(file)) != EOF){
count++;
}
}
else if(strcmp("-w",argv[1]) == 0){ //return value is 0
bool toggle = false; //keeps track whether the next space or line indicates a word
while((c = fgetc(file)) != EOF){
if(!toggle && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))){
toggle = true;
}
if(toggle && ((c == '\n') || (c == ' '))){
count++;
toggle = false;
}
}
}
Hope it works for you
You can read file line by line, it may simplify the task
int get_lines_chars(const char *path)
{
/* Open templorary file */
FILE *fp = fopen(path, "r");
if (fp != NULL)
{
ssize_t read;
size_t len = 0;
char *line = NULL;
unsigned int line_no, char_no;
line_no = char_no = 0;
/* Read line-by-line */
while ((read = getline(&line, &len, fp)) != -1)
{
int curr_line = 0;
while (*line)
{
curr_line++;
char_no++;
line++;
}
line -= curr_line;
line_no++;
}
/* Cleanup */
fclose(fp);
if(line) free(line);
printf("File has %d lines and %d chars\n", line_no, char_no);
return 1;
}
return 0;
}

No newline before EOF?

I was solving one of the exercises from K&R but I'm having a minor problem.
The exercise is to print a histogram of the length of words in its input.
Here's my code:
#include <stdio.h>
#define IN 1
#define OUT 0
int main(){
//Histogram of the length of words
int c, state, len, i;
state = OUT;
printf("Histogram\n");
while ((c = getchar()) != EOF){
if (c != ' ' && c != '\n' && c != '\t' && c != '\r'){
state = IN;
len++;
} else if (state == IN){
for (i = 0; i < len; i++){
putchar('[');
putchar(']');
}
len = 0;
putchar('\n');
state = OUT;
}
}
return 0;
}
The text file I used was:
Hello World! This is a text
The output of the program was:
Histogram
[][][][][]
[][][][][][]
[][][][]
[][]
[]
As it can be seen, the program terminated before printing out the histogram for the last word 'text'.
Is this because the text editor on Windows does not automatically put '\r\n' at the end? If so, how can I fix this problem?
Thank you.
Your loop end when getchar() return EOF so you never go in the else if at the end.
Example:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
printf("Histogram\n");
size_t len = 0;
bool running = true;
while (running) {
switch (getchar()) {
case EOF:
running = false;
case ' ':
case '\n':
case '\t':
case '\r':
if (len != 0) {
printf("\n");
len = 0;
}
break;
default:
printf("[]");
len++;
}
}
}
Move the tests around:
while (true)
{
const int c = getchar();
if (c != ' ' && c != '\n' && c != '\t' && c != '\r' && c != EOF)
{
state = IN;
len++;
}
else if (state == IN)
{
// ...
}
if (c == EOF) break;
}

InfixToPostfix code C

I code this in C, it's for infix to postfix translation, but It doesn't work and I can't understand why, I changed it many times...
The input should be a (supposed correct) expression between parenthesis in infix notation, the usual way we write with * and / having precedence on + and -, and the parenthesis giving precedence.
The postfix notation doesn't have parenthesis, for example:
If I put an input expression like((8-9)/6)
the expected output is 8 9 - 6 /
The program starts, but the output is really wrong, for example:
input: ((8-9)+7) output: 8-97 expected output: 8 9 7 - +
input: ((6+9)/7) output: 6+++++97 expected output: 6 9 + 7 /
here how I planned to do it:
1) If an operand is encountered, output it.
2) If a ( is encountered push it onto the Stack.
3) If an operator is encountered, then
Repeatedly pop from stack and output each operator which has same precedence as or higher precedence than the operator encountered.
Push the operator on the stack.
4) If a ) is encountered, then
Repeatedly pop from the stack and output each operator until a left parenthesis is encountered.
Remove the ) parenthesis.
#include <stdio.h>
#include <stdlib.h>
#define N 100
char ch;
struct stack {
char exp[N];
int index;
} stack;
void push (char ch) {
stack.exp[stack.index] = ch;
stack.index++;
}
char pop () {
stack.index--;
return stack.exp[stack.index];
}
int pr_op(char ch) {
if (ch == '+' || ch == '-')
return 0;
else if (ch == '*' || ch == '/')
return 1;
}
char translator(char ch) {
int i;
if (ch == '(')
{
push(ch);
}
else if (ch == ')')
{
i = stack.index;
while(stack.exp[--i] != '\0' && stack.exp[--i] != '(')
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
putchar(ch);
}
else
{
pop();
}
}
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
i= stack.index;
while(stack.exp[--i] != '\0' && pr_op(stack.exp[i])>=pr_op(ch))
{
putchar(ch);
}
push(ch);
}
else //operand
{
putchar(ch);
}
}
main(int argc, char *argv[])
{
ch = getchar();
stack.index = 0;
while ( ch != '\0'){
stack.exp[stack.index]=ch;
translator(ch);
stack.index++;
ch = getchar();
}
printf("\n");
return 0;
}
These lines are incorrect
char transl() {
int i;
if (ch = '(') // <--- this line
{
push(ch);
}
else if (ch = ')') // <--- this line
{
...
Since you are assigning values to ch at the same time as testing it. It should be == not = like this
char transl() {
int i;
if (ch == '(')
{
push(ch);
}
else if (ch == ')')
{
...
Your code has many minor mistake. So, here you go. But I don't undestand what the result you expect
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
char ch;
struct stack {
char exp[N];
int index;
} stack;
void push (char ch) {
stack.exp[stack.index] = ch;
stack.index++;
}
char pop () {
stack.index--;
return stack.exp[stack.index];
}
int pr_op(char ch) {
if (ch == '+' || ch == '-')
return 0;
else if (ch == '*' || ch == '/')
return 1;
}
char translator(char ch) {
int i;
if (ch == '(')
{
push(ch);
}
else if (ch == ')')
{
i = stack.index;
while(stack.exp[--i] != '\0' && stack.exp[--i] != '(')
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
putchar(ch);
}
else
{
pop();
}
}
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
i= stack.index;
while(stack.exp[--i] != '\0' && pr_op(stack.exp[i])>=pr_op(ch))
{
putchar(ch);
}
push(ch);
}
else //operand
{
putchar(ch);
}
}
main(int argc, char *argv[])
{
ch = getchar();
stack.index = 0;
while ( ch != '\0'){
stack.exp[stack.index]=ch;
translator(ch);
stack.index++;
ch = getchar();
}
printf("\n");
return 0;
}

Resources