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 !!!