Bad file descriptor after recursive function to open file in C - c

I want to do a error check in a openFile Function in C and on errno:2 I want to recursivly call again the same function.
I don't get the right answer, if I want to do fputs() after opened the file I get a Error (Bad file descriptor)
Here is my code:
void openFile(FILE **fstream, char* path, char* mode) {
*fstream = fopen(path, mode);
if(*fstream == NULL) {
printf("\nError number %2d : ",errno);
perror("Error opening file: ");
switch (errno) {
case 2:
printf("Creating file %s now...\n", path);
*fstream = fopen(path, "a+"); //Creating file in append-mode
if (fstream == NULL) {
perror("Couldn't open the file!\nError");
exit(EXIT_FAILURE);
}
fclose(*fstream); //Closing filestream
openFile(fstream, path, mode); //Recursive call of openFile() to re-open in read-mode
/* freopen(path,mode,fstream) */ //Doesn't work either
break;
default:
exit(EXIT_FAILURE);
break;
}
} else if (*fstream != NULL) {
printf("Successfully opened %s\n", path);
}
}
The call:
openFile(&fp, path,"r");
if (fputs("blabla\nblabla\n",fp) == EOF) {
perror("Unable to write file with fputs()");
}
What I'm doing wrong? I think it's at the point of the recursive call of the function, but what I have to do here? I don't get it..
Output is:
> .\a
Content of path: test.txt
Error number 2 : Error opening file: : No such file or directory
Creating file test.txt now...
Successfully opened test.txt
Unable to write file with fputs(): Bad file descriptor
PS: I am a beginner with C, I've read and youtubed a lot about pointer, but I don't get the mistake.
Thank you in advance

You opened the file with "r" yet you're attempting to write. You need "w" instead.

Related

C Prog fprintf not generating output

I've written the following code below and ran it without errors on both xcode and vscode. However, I wasn't able to get any output filename.txt. It wasn't in any of my folders.
Appreciate if anyone could help.
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp=NULL;
fp = fopen("filename.txt","w+");
if (fp!= NULL){
fprintf(fp,"%s %d","Hello",555);
}
fclose(fp);
return 0;
}
ran it without errors
fclose(NULL) is undefined behavior (UB), so it is not clear that there was no error when file failed to open.
Print something in both cases of opening success/failure - and with a '\n'. Useful to add error info.
Robust code checks all I/O operations.
#include <stdio.h>
#include <string.h>
int main() {
const char *filename = "filename.txt";
FILE *fp = fopen(filename,"w+");
if (fp == NULL) {
fprintf(stderr, "Unable to open <%s>\n", filename);
perror("fopen()");
} else {
printf("Success opening <%s>\n", filename);
if (fprintf(fp,"%s %d","Hello", 555) < 0) {
fprintf(stderr, "Print failure with <%s>\n", filename);
perror("fprintf()");
}
if (fclose(fp) == EOF) {
fprintf(stderr, "Failed to close <%s>\n", filename);
perror("fclose()");
}
}
return 0;
}
I've also tried the perror method and it shows filename.txt: Permission denied. Later.
Check if filename.txt is read-only, or in use by another application (editor?), or other permission limitations.
If the file wasn't successfully opened, then the code does nothing (apart from closing a null FILE-pointer, which is undefined). You should use perror() to indicate why it couldn't be opened:
const char *const filename = "filename.txt";
FILE *const fp = fopen(filename, "w+");
if (!fp) {
perror(filename);
return EXIT_FAILURE;
}
fprintf(fp, "%s %d", "Hello", 555);
There's a good chance that you have an existing filename.txt that isn't writable by you, or you are in a directory where you can't create a new file, but we'll need the error message to actually determine why it wasn't opened.
Alternatively, you're running in a different working directory to where you thought you were - that's something you should investigate (perhaps produce some logging to stderr to indicate where the file is being created).
I ran your code and it works just finecheck this image
but, how are you compiling it and did you remember to run the a.out/execution?

How to exit safely from a loop while working on a growing input file?

I am reading a growing input file, and do some work and write the info to the output file. I have some conditions to work on the growing file. But I am failing at exiting from the loop.
FILE *logfile;
int main(int argc, char *argv[])
{
char *filename;
char *logfilename;
FILE *infile;
char line_buf[255];
char *line;
sleep(3);
if (argc < 3) {
fprintf(stderr, "Usage: %s <filename> <logfile>\n",
argv[0]);
return -1;
}
filename = argv[1];
logfilename = argv[2];
infile = fopen(filename, "rb");
if (infile == NULL) {
fprintf(stderr, "Failed to open file\n");
return -1;
}
logfile = fopen(logfilename, "w");
if (logfile == NULL) {
fprintf(stderr, "Failed to open logfile - are permissions correct?\n");
return -1;
}
while(1){
line = fgets(line_buf, sizeof(line_buf), infile);
if (line == NULL){
if(feof(infile))
clearerr(infile);
failedReads++;
usleep(25000); //wait for the data from live file
continue;
}
else{
if(feof(infile))
break;
}
...........
//do some work
...........
}
fclose(infile);
fclose(logfile);
}
My output log file is getting the data only after the input file stops growing(means at the end of execution). I want my output logfile to get the data by time(means output file is not growing). I have a python script for create a growing file(If anyone really wants to work my issue).
#/usr/bin/python
import time
with open("input.txt") as f:
fileoutput = f.readlines()
with open("out.txt", "a+") as f1:
for line in fileoutput:
f1.write(line)
f1.flush()
time.sleep(0.01)
Code is waiting indefinitely for additional data. Code just waits longer and longer with usleep(25000*failedReads).
// Ineffective code
if (line == NULL){
if(feof(infile))
clearerr(infile);
failedReads++;
usleep(25000*failedReads); //wait for the data from live file
continue;
}
else{
if(line == NULL) // this can never be true!
if(feof(infile))
break;
}
"to get the data by time(means output file is not growing" implies there should be an upper bound of time that if the input file fails to provide more data, quit the loop.
Look for 2 successive read failures. If waiting after the first failure does not provide more data, time to leave.
// instead
bool failed_read_flag = false;
while(1){
line = fgets(line_buf, sizeof(line_buf), infile);
if (line == NULL){
if (failed_read_flag) {
break; // 2 successive read fails
}
if(!feof(infile)) {
break; // Rare input error just occurred.
}
clearerr(infile);
failed_read_flag = true;
usleep(25000 /* us */); //wait for the data from live file
continue;
}
failed_read_flag = false;
// Do some work
}
Strange to open a file with infile = fopen(filename, "rb"); and then use it with fgets().
It the file is a text file, use fopen(filename, "r"). If the file is binary, use fread().

How to use revieced message from client as file path in server side in C?

I am trying to write a server app in C that gets file path from client and sends the file content back to the client. When i receive the client message and try to use as file path, file becomes NULL and it can not be read.
char server_reply[2000];
if( recv(sock , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
break;
}
FILE *fp = fopen(server_reply,"rb");
if(fp==NULL)
{
printf("File open error");
return 1;
}
I test my code getting file path via scanf and it works.
char path[2000];
printf("Enter path : ");
scanf("%s" , path);
FILE *fp = fopen(path,"rb");
if(fp==NULL)
{
printf("File open error");
return 1;
}
i couldn't figure out what is the difference between server_reply and path. The definitions of two variables both char array. I will appreciate if i can get any clue about it, thanks.
I would like to give following recommendations.
1) make sure you receive absolute path.
2)From client make sure you send a null terminated string.
3) Try to use udp protocol, to get complete information in one shot/ or use your own protocol over tcp(say you encode string length and type(tlv encoding))
Make sure the file server_reply exists first. fopen() will return NULL if the pointed file path does not exist. It's a simple way to check if the file exists:
FILE* fptr = fopen(filename, "r");
if (fptr != NULL)
{
fclose(fptr);
printf("File exists\n");
} else {
printf("File doesnt exist\n");
}

my copy file function isn't working as expected

Here is a simple program that should copy the content of one
file named copyme into a file here. I have created copyme with a little text in it by the following commands:
touch copyme.txt
open copyme.txt
Then I typed in text, and saved the file with
touch copyme.txt command.
Then I compiled a program:
// Program to copy one file ot another
#include <stdio.h>
int main (void)
{
char in_name[64], out_name[64];
FILE *in, *out;
int c;
// get file names from user
printf("Enter name of file to be copied: ");
scanf("%63s", in_name);
printf("Entere name of output file: ");
scanf("%63s", out_name);
// open input and output files
if ( (in = fopen(in_name, "r")) == NULL)
{
printf("Can't open %s for reading.\n", in_name);
return 1;
}
if ( (out = fopen(out_name, "w")) == NULL)
{
printf("Can't open %s for writing.\n", out_name);
return 2;
}
while ((c = getc(in)) != EOF)
putc(c, out);
// Close open files
fclose (in);
fclose (out);
printf("File has been copied\n");
return 0;
}
And ran it in terminal.
Here is the output:
Enter name of file to be copied: copyme
Entere name of output file: here
Can't open copyme for reading.
The compiler doesn't recognize copyme file, although it is
physically exists in the folder (I see it, I open it, I read
it).
I would be grateful for help. I am new to this things.
Thank you!
change
if ( (in = fopen(in_name, "r")) == NULL)
{
printf("Can't open %s for reading.\n", in_name);
return 1;
}
to
#include <errno.h>
if ( (in = fopen(in_name, "r")) == NULL)
{
perror("Can't open file for reading.\n");
return 1;
}
you will get a human readable message telling you why it cant read the file

How to use file structure?

I am having a small problem, I have the current file structure:
And this is my code:
#include <stdio.h>
#include <stdlib.h>
const char FILE_NAME[] = "inputfile.txt";
int main()
{
FILE *in_file; /* input file */
in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}else{
printf("File opened %s\n", FILE_NAME);
}
fclose(in_file);
return (0);
}
And I get this error:
Cannot open inputfile.txt
But the file is right there.
Can someone help me?
(If I change the "r" to "w" I can write to the file, but I can't find the file on my SSD)
The program will look for the file in the current working directory. This is most likely the same directory as the compiled executable.
If you are using an IDE, check the project settings and check where the compiled executable is placed. Then either copy the textfile to that directory manually or edit the project so that building it copies the file automatically.
If you are working from the command line (assuming your compiler is called gcc):
cd ~/Documents/programming/c/PracticalC/chapter14
gcc -Wall ch14pexercise1.c -o prog
./prog
include
include
const char FILE_NAME[] = "inputfile.txt";
int main()
{
FILE *in_file; /* write file */
in_file = fopen(FILE_NAME, "w");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}else{
printf("File opened %s\n", FILE_NAME);
}
fclose(in_file);
/read file/
FILE *in_file; /* input file */
in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}else{
printf("File opened %s\n", FILE_NAME);
}
fclose(in_file);
return (0);
}
If it work cheak path

Resources