trying read and write on the same code in c program - c

Help I'm trying to write the data in the file. then, trying to read it back, but its not working.
#include <stdio.h>
int main(void) {
FILE *fptr = fopen("try.txt", "r+");
char line[1000];
fprintf(fptr, "i have new number = 1425");
while (fgets(line, 1000, fptr)) {
printf("%s",line);
}
return 0;
}

You must use a positioning function such as rewind() or fseek() between read and write operations.
Beware that the update mode for streams is very confusing and error prone, you should avoid using it and structure your programs accordingly.
Incidentally, your program will fail to open try.txt if it does not already exist, but you do not check for fopen failure so you will get undefined behavior in this case.
Here is a modified version:
#include <stdio.h>
int main(void) {
char line[1000];
FILE *fptr = fopen("try.txt", "w+");
if (fptr != NULL) {
fprintf(fptr, "I have new number = 1425\n");
rewind(fptr);
while (fgets(line, sizeof line, fptr)) {
printf("%s", line);
}
fclose(fptr);
}
return 0;
}

Related

fopen() fails but seems to not return NULL?

I have got the following code:
#include <stdio.h>
#include "config.h"
#include <errno.h>
char buffer[50];
long long bufSize = 50;
FILE* fptr;
char* readConfig(char* buffer, size_t bufSize) {
fptr = fopen("config.txt", "rt");
if (fptr == NULL) {
return "error opening config file: %s", strerror(errno);
} else {
if ((fgets(buffer, bufSize, fptr)) == NULL) {
fclose(fptr);
return "error reading config file: %s", strerror(errno);
}
else {
fclose(fptr);
return buffer;
}
}
}
For test purposes I deleted the config.txt file so that the fopen() function should return NULL.
What wonders me is that fopen("config.txt", "rt"); fails, but when debugging the code it just skips the "if (fptr == NULL) {...}" part and directly jumps out of the function.
When going on with the debugging process, I get the following error when trying to work with the return Value of readConfig() "0xC0000005: Access violation reading location 0xFFFFFFFFA4E0EB70"
Cannot compile your code as you shared a snippet (no main()) and didn't include config.h.
#include <string.h> for strerror().
Suggest caller passes in local variables instead of global variables.
Instead of hard-coding the size in both buffer[50] and bufSize = 50; use sizeof to determine the size of the array. The other good alternative is to define a constant.
The fopen() mode "t" isn't standard, so either leave it out or tag your program with windows or whatever.
As you return on error, eliminate the unnecessary else & indentation.
The expression return "error opening config file: %s", strerror(errno); doesn't work the way you expect, it will evaluate the first part in void context then return the 2nd part strerror(errno). I was not able to otherwise reproduce any ill effects.
fgets() return NULL on eof or error but not appear to set errno. You can use feof() and/or ferror() to tell which if needed.
After the call to fgets() you call fclose() prior to inspecting errno, so it have the status of the fclose() call instead.
It's a bad design to return either error message or the value you read from the file as you cannot tell them apart. Changed to return NULL on success.
#include <errno.h>
#include <stdio.h>
#include <string.h>
char *readConfig(char *buffer, size_t bufSize) {
FILE* fptr = fopen("config.txt", "r");
if(!fptr)
return strerror(errno);
if(!fgets(buffer, bufSize, fptr)) {
fclose(fptr);
return "fgets eof/error";
}
fclose(fptr);
return NULL;
}
int main(void) {
char b[50];
const char *error = readConfig(b, sizeof b);
if(error) {
printf("error: %s\n", error);
return 1;
}
printf("%s", b);
}
Consider having caller open the file and pass in the FILE *. It gives you the flexibility, for instance, to use stdin as the file handle.
I prefer using goto instead of the multiple returns when resource cleanup is required. It's a bit more verbose here but each error case is handled the same way. When you swap the arguments you can document how they are related with recent compilers:
char *readConfig(size_t bufSize, char buffer[bufSize]) {
char *r = NULL;
FILE* fptr = fopen("config.txt", "r");
if(!fptr) {
r = strerror(errno);
goto out;
}
if(!fgets(buffer, bufSize, fptr)) {
r = "fgets eof/error";
goto out;
}
out:
fptr && fclose(fptr);
return r;
}

Problem with reading and writing to a file at the same time

I am trying to read and write the file at the same time in C. I can write to the file but couldn't read from the file. Any suggestions?
#include <stdio.h>
int main()
{
char *str = "C programming language";
char str1[100];
FILE *fptr = fopen("Output.txt", "r+");
if (fptr == NULL)
printf("Could not open file!");
fputs(str, fptr);
fgets(str1,100,fptr);
fclose(fptr);
printf("%s", str1);
return 0;
}
Please assume that the output.txt file already exists on my computer.
Quoting http://www.cplusplus.com/reference/cstdio/fopen:
For files open for update (those which include a "+" sign), on which
both input and output operations are allowed, the stream shall be
flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a
reading operation that follows a writing operation. The stream shall
be repositioned (fseek, fsetpos, rewind) before a writing operation
that follows a reading operation (whenever that operation did not
reach the end-of-file).
After you've done the write, you should seek to beginning of the file. For that call rewind().
Here's the corrected code:
#include <stdio.h>
int main()
{
char *str = "C programming language";
char str1[100];
FILE *fptr = fopen("Output.txt", "r+");
if (fptr == NULL)
printf("Could not open file!");
fputs(str, fptr);
rewind(fptr); // seek to beginning
fgets(str1,100,fptr);
fclose(fptr);
printf("%s", str1);
return 0;
}
You will need to re-position the offset to beginning to read that string.
After your write, the pointer is at the offset which is past the string your wrote.
#include <stdio.h>
int main()
{
char *str = "C programming language";
char str1[100];
FILE *fptr = fopen("Output.txt", "r+");
if (fptr == NULL)
printf("Could not open file!");
fputs(str, fptr);
fseek(fptr, 0, SEEK_SET); // add this
fgets(str1,100,fptr);
fclose(fptr);
printf("%s", str1);
return 0;
}
./main.out
C programming language

How to get fpointer to point to an html file in the network?

I'm basically trying to get to print a string from the login page of my router (well, the HTML file) but i don't know how to get c to point to a url.
I started with this, which obviously wasn't going to work but I'm new to this and I had to try.
#include <stdio.h>
char line [255];
int main()
{
FILE * fpointer = fopen("http://192.168.0.1/login.html", "r");
fgets(line, 255, fpointer);
printf("%s", line);
fclose(fpointer);
return 0;
}
I have almost no idea of programming, i just want to know how can I do what this program should be able to do with any file in my computer, but with a url.
Thank you!
You may use popen function with curl command.
FILE *fp = popen("curl http://192.168.0.1/login.html", "r");
if (fp == NULL) {
// Error. throw Exception or report
}
char buffer[MAX_SIZE];
while (fgets(buffer, MAX_SIZE, fp) != NULL) {
processChunk(buffer);
}
pclose(fp);

the function fgetc is not working properly

i'm testing the fgetc() function but it doesn't work properly (i have used this function befor so i know how it works)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = NULL;
int n;
file = fopen("test.txt", "w+");
if(file != NULL)
{
fputs("ab", file);
printf("%c", fgetc(file));
}
else
{
printf("error");
}
return 0;
}
the output should be "a" but it's somthing else
The file is opened for both writing and reading but you need to fseek to the correct place in the file (here, the beginning). In particular, when switching between writing and reading you need to fseek or fflush.
When the "r+", "w+", or "a+" access type is specified, both reading
and writing are enabled (the file is said to be open for "update").
However, when you switch from reading to writing, the input operation
must encounter an EOF marker. If there is no EOF, you must use an
intervening call to a file positioning function. The file positioning
functions are fsetpos, fseek, and rewind. When you switch from writing
to reading, you must use an intervening call to either fflush or to a
file positioning function.
In any case, after writing to the file, the file pointer is in the wrong place to read what was just written.
So the code becomes
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file = NULL;
file = fopen("test.txt", "w+");
if(file != NULL) {
fputs("ab", file);
fseek(file, 0, SEEK_SET);
printf("%c", fgetc(file));
fclose(file);
}
else {
printf("error");
}
return 0;
}
And if you want to continue writing to the file, you must fseek to its end.
Your error is that you are trying to read a file that has been opened for writting. You should write inside it, then close the file and reopen it for reading. This code will show what I am telling:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fileRead, *fileWrite = NULL;
int n;
fileWrite = fopen("test.txt", "w+");
if(fileWrite != NULL)
{
fputs("ab", fileWrite);
fclose(fileWrite);
}
else
{
printf("error");
}
// Open again the file for read
fileRead = fopen("test.txt", "r");
printf("%c", fgetc(fileRead));
fclose(fileWrite);
// End function
return 0;
}

I want to copy my in file on to my out file.

In this code I opened my files in my open_file function. Then the process_file function needs to copy the text from my in file and Copy it to an out file. Right now it produces a new file but it is blank. It does not give me any error messages. I do not know what is wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_LEN 100
FILE* open_file(char prompt[], char mode[]);
FILE* process_file(FILE* in, FILE* out);
int main(int argc, const char * argv[]) {
FILE* in = NULL;
FILE* out = NULL;
printf("MAD-LIBS Text Processor\n");
printf("The Program will open a mad-libs file, ask you to fill various words, and produce a funny story.\n");
open_file("Enter mad-lib file name:\n", "r");
open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
fclose(in);
fclose(out);
return 0;
}
/* open_file = prompts user for file name & and attempts to open it, if it fails it prompts the user again. */
FILE* open_file(char prompt [], char mode[]) {
char filename[255];
FILE* in;
do {
printf("%s", prompt);
scanf("%s", filename);
in = fopen(filename, mode);
if (in == NULL) {
printf("Unable to open file: %s. Try Again!\n", filename);
}
} while(in == NULL);
return in;
}
/* process_file = processes entire input file and writes it to output file */
FILE* process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
char NewContent[MAX_LEN];
//gets whats in file in
while(fgets(content, content[MAX_LEN], in) != NULL) {
fputs (content, stdout);
strcat(NewContent, content);
}
// copies it
while (fgets(content, content[MAX_LEN], in) != NULL) {
fprintf(out, "%s", content);
}
printf("Successfully copied file\n");
return in;
}
You never assign the FILE* from open_file function to your variable, so it never gets processed.
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
You are not storing the FILE pointers that open_file is returning, so in
and out remain uninitialized.
You have to do:
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
Also your process_file is wrong. NewContent is not initialized, when you do
strcat(NewContent, content);
this yields undefined behaviour. Declare NewContent like this:
char NewContent[MAX_LEN] = { 0 };
so that it is properly \0-terminated.
Also depending on the size of the file you are copying, MAX_LEN might not be
long enough to hold the whole file. In that case you would overflow the buffer.
It would be better not to use NewContent in the first place and write to out
in the same reading loop:
FILE* process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
//gets whats in file in
while(fgets(content, MAX_LEN, in) != NULL) { //<- your fgets was wrong
fputs (content, stdout);
fprintf(out, "%s", content); // or fputs(content, out);
}
printf("Successfully copied file\n");
return in;
}
And you were calling fgets incorrectly (look at my corrected code)
Also bear in mind, that you did have 2 loop doing while(fgets(...) != NULL.
Well, the first loop ends, that's because fgets returns NULL, most likely
because the whole file was read or there was an I/O error. In either case
subsequent calls of fgets will return NULL as well, so your second loop
would not even be executed at all.

Resources