Program asks for input and stores it in a variable, then confirms the operation printing the content of the file. Or at least it had to, when the program ends it doesn't print the file content, I can't seem to find an answer, I've been looking in the docs but can't really figure it out.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * file1 = fopen(".out", "w ");
char *s = malloc(513);
fgets(s, 513, stdin);
if (fprintf(file1, "%s", s) < 0)
{
printf("Something failed while writing to the file\n");
return 1;
}
else
{
char *t = malloc(513);
fread(t, sizeof(char), 1, file1);
printf("Success! Input was: %s \n", t);
return 0;
}
}
P.S: Very new to C, though it may seem obvious for you I have no clue whatsoever.
CodePudding user response:
There are 2 issues here,
1 - you wrote to the file handler and you are trying to read from that point onwards - you didnt rewind
the file pointer!
2 - you are just reading 1 character and not the amount you wrote to it!
#include <string.h>
...
int n = strlen(s);
rewind(file1); // rewind before read
fread(t, sizeof(char), n, file1); // read as much as you wrote
CodePudding user response:
Some problems in your code:
- You are not checking the return value of
fopen()
,malloc()
,fgets()
andfread()
. - You are writing one character to the output stream, without rewinding it.
Here's how your code should look like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE * file1 = fopen(".out", "w ");
if (!file1) {
printf("Could not open file.\n");
return 1;
}
const size_t n = 513; // Use constants, not litterals.
char *s = malloc(sizeof(char) * n);
if (!s) {
printf("Internal error.\n");
fclose(file1);
return 1;
}
if (!fgets(s, n, stdin)) {
printf("Input failed.\n");
fclose(file1);
return 1;
}
if (fprintf(file1, "%s", s) < 0) {
printf("Something failed while writing to the file\n");
fclose(file1);
return 1;
}
char *t = malloc(sizeof(char) * n);
if (!t) {
printf("Internal error.\n");
fclose(file1);
return 1;
}
rewind(file1);
int ret = fread(t, sizeof(char), n, file1); // Read n characters, not 1.
if (ret != strlen(s)) {
if (feof(file1)) {
printf("Error reading .out: unexpected end of file.\n");
} else if (ferror(file1)) {
perror("Error reading .out");
}
fclose(file1);
return 1;
}
printf("Success! Input was: %s \n", t);
}