I am trying to read a file every time the user inputs 1 but i am facing an unexpected behaviour,
This is my code.
#include <stdio.h>
#include <string.h>
char* read_file(char* file_name){
FILE *fp = fopen(file_name, "r");
if (fp == NULL)
{
printf("Error: could not open file %s", file_name);
return "";
}
// reading line by line, max 256 bytes
const unsigned MAX_LENGTH = 30000;
char buffer[30000];
char data[MAX_LENGTH];
memset(buffer, '\0', MAX_LENGTH);
while (fgets(buffer, MAX_LENGTH, fp)){
strcat(data, buffer);
// strcat(data, "\n");
}
// close the file
fclose(fp);
char* return_data = &data[0];
return return_data;
}
void send_data(char* file_name){
printf("\n\n %s\n", read_file(file_name));
}
int main()
{
int cont = 1;
while(cont){
send_data("try/try.txt");
scanf("%d", &cont);
}
}
What is happening is when it is giving the output the first time it gives the correct result but on the second time it adds the prev result and new result and prints it. Is there any way i can correct it.
Here is the output log
tusharsing@techie-Latitude-3520:~/Desktop/Project/project/temp$ ./filetry
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 12
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
1
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 12
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 12
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
^C