fopen c with multiple files - c

In my software I have to read multiple txt databases in a serial way, so I read the first, then I do something with the info I got from that file, than I open another one to write and so on.
Sometimes I got an error on an opening OR creation of a file, and then I got errors on all the following opening/creation, which uses different functions, different variables, different files.
So for example I call the function below, which uses two files, and I got an error "* error while opening file -%s- ..\n", then all the other fopen() in my code goes wrong!
This is an example of code for one single file:
FILE *filea;
if((filea=fopen(databaseTmp, "rb"))==NULL) {
printf("* error while opening file -%s- ..\n",databaseTmp);
fclose (filea);
printf("---------- createDatabaseBackup ----------\n");
return -1;
}
int emptyFolder=1;
FILE *fileb;
if((fileb=fopen(databaseBackup, "ab"))==NULL) {
printf("* error while opening file -%s- ..\n",databaseBackup);
fclose (fileb);
printf("---------- createDatabaseBackup ----------\n");
return -1;
}
else {
int i=0;
char c[500]="";
for (i=0;fgets(c,500,filea);i++) {
fprintf(fileb,"%s",c);
emptyFolder=0;
}
}
fclose(fileb);
fclose(filea);

There is an upper limit on the number of open handles for a given process. May be you have a handle leak in your program ?
Error while creating a file typically means you don't have access permission to the parent folder .
Those error log messages belong to your program . You can enhance it further. There is an errnum set by the os as fopen is essentially a system call. You can print that error number and get more info about your issue.

If fopen returned NULL, the file wasn't opened, so there's no point in trying to fclose it.

You should check the return value of fgets besides whether it is 0 or not. If it reads 500 characters and the buffer is not null-terminated, the fprintf will attempt to write more characters than is allocated for c

Related

canĀ“t open txt file

#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
Output is Error! opening file
I have program and txt file in same dir.
How can I direct access to that file?
To diagnose, use the system command to issue a ls or dir depending on your platform. That will tell you where you are running from. Odds are it is a different location than the files you are trying to open.
As suggested in the comment, try replacing printf with perror
if ((fptr = fopen("program.txt", "r")) == NULL)
{
perror("Error");
// Program exits if file pointer returns NULL.
exit(1); // Exiting with a non-zero status.
}
perror prototype is
void perror(const char *str)
where str is the C string containing a custom message to be printed before the error message itself.
However some causes of the of the file not being read are
File is not present in the current working directory. If this is the case, rectifying the path should fix the issue.
The program might not have the permissions to read from the file usually because of a setting related to discretionary access control. Perhaps do a chmod with file?
I made a quick run of your program on TURBOC++ by Borland and it executed without complaining any sort of Warning or Error
As mentioned in the earlier posted answers, you should replace printf by perror
CURRENT REPLACE BY
printf("Error! opening file"); perror("Error! Opening File.");
As in your case of file not found printf("Error! opening file"); will result in :
Error! Opening file.
However in case of perror("Error! Opening File."); if the file program.txt does not exist, something similar to this may be expected as program output
The following error occurred: No such file or directory
The difference is obvious from above explanations.
Regarding your program, I am making an assumption that either your path to the file is wrong or there is some problem with your compiler.
Try to open your file in w+ mode also to ensure that the file exist.

Can not open files with c

Im supposed to write a program that opens an excel file, reads the numbers on the file, multiplies them by 9.8 and the shows the answer in another excel gile.
I wrote this, and I did not get any errors in the compiler, but when I run it, it does not open any files. How do I make it open the files?
#include <stdio.h>
int main() {
FILE *archivo;
FILE *archivoSalida;
int masa;
float peso;
archivo = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoEntrada.txt", "r");
archivoSalida = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoSalida.txt", "r");
if (archivo != NULL)
{
printf("The file was opened succesully");
while (fscanf(archivo,"%d", &masa)!= EOF)
{
peso=masa*9.81;
fprintf(archivoSalida, "%f\n", peso);
}
}
else
{
printf ("Error");
}
fclose(archivo);
fclose(archivoSalida);
return 0;
}
You'll want to fopen the output file ("archivoSalida") with mode "w" (for write) instead of "r" (for read). See e.g. http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html.
You do check if the input file could be opened (if (archivo != NULL)). Why don't you do the same for the output file?
Upon an error, you should output which error occured from errno, e.g. via perror(...). That should help in finding the actual problem.
Your file denominated by archivoSalida is opened in read mode ('r').
You should also check the return codes of read/writes functions to be sure everything happen as wanted.
The file names look Windows-ish. Is it possible that all of the forward slashes (/) that you have in both file names should really be back slashes (\)?

Each time the C code exits after reading the certain number of files

I have two sets of data files "P" (position) and "F" (force) files. Separately (in two different codes) the codes can open and read all "P" and "F" files. When I try to read them together in single code, the code opens and reads data from files, but only 1004 of "P" file and then exits. I cannot even debug it as it shows a normal exit.
What should I do to debug the code? The computer has enough memory and the data files are not large. Here is part of the code which opens the files:
...
FILE *finput1, *finput2;
char filename[160], filename2[160];
...
for (i=0;i<N_f1;i++) {
sprintf(filename, "F%d.dat", i);
finput1=fopen(filename,"r");
if( finput1 == NULL ) {
printf(" Could not open F file!\n");
return 0;
}
sprintf(filename2, "P%d.dat", i);
finput2=fopen(filename2,"r");
if( finput2 == NULL ) {
printf(" Could not open P file! %d \n",i);
return 0;
}
...
You are running into a maximum number of file descriptors. Close each file after you open the next one.
The files that can be open simultaneously is limited, you can check the value of FOPEN_MAX in stdio.h.
Note that it is the minimum number of files that the implementation guarantees, you might open more than it in practice.

storing logs/error message on C programming

When an error occurs, I would like my C code to store the error before exiting the program. Is it advised to store the stderr to a file (e.g., /home/logs.txt) or would it be advised to use a different method to keep the logs/error report (considering the programming environment is Linux). E.g., for the code below, how I could apply the method to store the logs/error message on /home/log.txt or /home/log
FILE *fp1;
fp1 = fopen("/sys/class/gpio/export","w");
if(fp1 == NULL){
fprintf(stderr, "errno:%s - opening GPIO136 failed - line 739\n ", strerror(errno));
close(fp1);
exit(1);
}
Thank you.
If stderr is always used to print out all your error message, so, you can redirect output to a specific file.
$ program 2>~/logs.txt
For a better logging tool, you can use:
syslog standard function.
log4c library.
If you want to store the error, stderr is probably not a good choice because you'll need to pipe stderr to a file every time you run the program.
If you want to write to /home/log.txt, open a FILE pointer to it and write with fprintf the same way you tried to open /sys/class/gpio/export and write to that instead of stderr. Also be sure to open the log file with append mode.
FILE *fp1;
fp1 = fopen("/sys/class/gpio/export","w");
if(fp1 == NULL){
FILE *fpErr = fopen("/home/log.txt", "a");
if(fpErr != NULL)
fprintf(fpErr, "errno:%s - opening GPIO136 failed - line 739\n ", strerror(errno));
close(fpErr);
close(fp1);
exit(1);
}

Help with opening a file in C on Xcode

I'm trying to open a simple .rtf file called test in C. I'm using Xcode. My code is:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, const char * argv[]) {
FILE *filePtr;
filePtr = fopen("test.rtf", "r");
if (filePtr == NULL) {
fprintf(stderr, "Can't open \"test\"\n");
exit(EXIT_FAILURE);
}
else {
printf("File open successful\n");
int x;
/* read one character at a time until EOF is reached */
while ((x = fgetc(filePtr)) != EOF) {
printf("%c", x);
}
}
fclose(filePtr);
return 0;
}
I have the test.rtf file in the same directory as my Xcode.proj directory. My output is "File open successful", however I do not get anything read from the file. Am I doing this right? Thanks.
There's nothing wrong with that code at all. I tested it (albeit not in Xcode) with a file and the transcript was:
pax> echo hello >test.rtf
pax> ./qq.exe
File open successful
hello
So the obvious think to ask is what happens when you examine test.rtf? Does it actually have any content? Because, when I do:
pax> rm test.rtf ; touch test.rtf
pax> ./qq.exe
File open successful
I get the same behaviour you observe.
Also try renaming it to test2.rtf temporarily and make sure you get the error. It's possible it may be opening a different copy of the file than what you think (this often happens in Visual C since the directory the program runs in is not always what developers think at first).
It looks right.
As for the lack of output, two possibilities:
Are you sure the file has some content? Maybe ls -l test.rtf or dir test.rft
Possibly it has some control characters which cause the terminal to which it is written to suppress output.
Try moving test.rtf to your build directory. If your project is named MyProject, move it to MyProject/build/Debug/.
I can think of two things that could cause this problem. Either there is an error when calling fgetc, or you are getting output that you don't recognize.
fgetc() will return EOF when the end of the file is reached, or an error occurs. To determine if it's an error, just after your while loop try:
if (ferror(filePtr) != 0) printf("error: %d.\n", errno);
A .rtf file is not a plain text file. It likely contains a bunch of formatting information. You are expecting to see "Hello . . . ". but what you may actually see is something like:
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf250
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040
\f0\fs24 \cf0 Hello . . .
And you are just assuming that is GDB output, not your program's output.
Based upon your recent comments, I think you have an empty file test.rtf in the directory your program is run in, and your real test.rtf file is in some other directory. Maybe your fopen() call at some point was fopen("test.rtf", "w"); instead of fopen("test.rtf", "r");, and you later modified it.
To see the directory your program is running in, add the following to your program after the FILE *filePtr; line:
char pwd[512];
if (getcwd(pwd, sizeof pwd) != -1)
printf("In directory %s\n", pwd);
else
fprintf(stderr, "Need bigger buffer, change '512' above\n");
Then, you can open a terminal, do cd <directory>, and test for yourself if the file you want is the file your program is opening.
You probably want this file to be plain text, not rich text. Rich text has a lot of formatting encoded into the file.

Resources