I am trying to write a character to a file in C, but this code:
case 4: //If the user types 4 (reset)
FILE * fp;
FILE *fp;
fp = fopen("settings.txt", "w");
fprintf(fp, "a");
int fclose(FILE * fp);
break;
shows this error:
fileio.c:72:5: error: expected expression
FILE * fp;
(Yes, I know I used file * fp two times, but without both, it shows even more errors.)
How can I fix this?
There's a few issues going on here. You can't declare new variables in a case statement. Declare your fp outside the switch. Also, only declare it once, and when you close it, call the function instead of writing a new function prototype:
fclose(fp);
There are several issues with this code. The main one you are facing is that you cannot declare variables directly under a case statement. If you need to declare variables there, you must enclose the code block in curlies, thus:
case 4: //If the user types 4 (reset)
{
FILE *fp;
fp = fopen("settings.txt", "w");
fprintf(fp, "a");
fclose(fp);
break;
}
Note that I also fixed your fclose() call--what you had was incorrect.
In the close statement you define a new pointer again. Try just
FILE *fp;
fp = fopen("settings.txt", "w");
fprintf(fp, "a");
fclose(fp);
Related
I want to open file named ex1, ex2, ex3 ...exn etc.
Now when i put the value of n like, n=1, ex1 will be opened
for, n=2, ex2 file will be opened and then I will read or write my c program output array from or into it.
can the name of the file be given as a string?
As I am new with programing please help me to solve this problem.
Normally when you open a file you use the function fopen
fp = fopen ("file.txt", "w+");
if (fp == NULL)
{
exit(1); // Or you can raise some error code and return if this code is in a function.
}
// Process the file
Now in your case, you need to manipulate the filename. So you can take a C string for this.
char filename[10];
// N is set from code above
sprintf(filename,"ex%d",N);
fp = fopen (filename, "w+");
// Further behaviour is same
I am currently writting a program on Linux to get the current CPU usage from /proc/stat and print in to a .txt file. However, whilst writting to the file, I am unable to print a new line, and the output prints OVER the old one...
I would like to print the new line under the previous one, but using the "\n" or "\r" characters didn't work.
The code is here:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void checker();
int main(){
long double a[4], b[4], loadavg;
FILE *fp;
char dump[50];
for(;;){
fp = fopen("/proc/stat","r");
checker();
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&a[0],&a[1],&a[2],&a[3]);
fclose(fp);
sleep(1);
fp = fopen("/proc/stat","r");
checker();
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&b[0],&b[1],&b[2],&b[3]);
fclose(fp);
fp = fopen("CPU_log.txt", "w");
checker();
loadavg = ((b[0]+b[1]+b[2]) - (a[0]+a[1]+a[2])) / ((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3]));
fprintf(fp, "Current CPU Usage is: %Lf\r\n", loadavg);
fclose(fp);
}
return 0;
}
void checker(){
FILE *fp;
if (fp == NULL){
printf("Error opening file!\n");
exit(1);
}
}
It seems that you need to append new data to existent file (i.e. do not overwrite) instead of creating of empty file each time. Try this:
fp = fopen("CPU_log.txt", "a");
Second argument "a" means "append":
Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
Also it seems reasanoble to modify your function checker:
void checker(FILE *fp) {
if (fp == NULL){
perror("The following error occurred");
exit(EXIT_FAILURE);
}
}
Inside for loop, You are opening CPU_log.txt file in write mode.
fp = fopen("CPU_log.txt", "w");
Mode w will truncate the file to zero length or create file for writing.
Open file in append mode. This will not overwrite the contents.
fp = fopen("CPU_log.txt", "a");
You need to open the files outside the for()-Loop, otherwise, your file is overwritten continuosly. Or you need to open your file with "a" instead of "w", which appends to the file instead of throwing everything away.
Besides, what is %Lf supposed to do? (Should be %f!)
Hi guys i have a problem when I try to open a file. In a function when i try to read an existing text file, after i initialized the file pointer i still get the error "cannot open the file", this is the code:
FILE * fp;
fp = NULL;
fp=fopen("results.txt","r");
if(fp==NULL){
printf("error!");
exit(1);
}
using the debugger i can see the fp initialized to NULL, as requested. In the next order i can see its value changed to '0x751d9c68'.
So now it's not NULL, but the program still prints error.
PS: I used the same code to open another file in another program (that works): as always the initial value of fp is NULL, then it's changed to '0x751d9c68' (yes, it has the same value in both programs), but this time works, because fp is in fact different from NULL.
PPS: I'm using Codelite, if that helps.
EDIT: adding a printf("%p\n", fp); prints this "751D9C68"
Atleta * leggiRisultati (char fileName [], int * dim){FILE * fp; int count, i;
Atleta temp;
fp = NULL;
fp=fopen(fileName,"r");
printf("%p\n", fp);
if(fp==NULL){
perror("Error");
}
while (fscanf (fp, "%s%s%d%d%d", temp.cod, temp.nome, &temp.tN, &temp.tB, &temp.tC)== 5)
count ++;
rewind (fp);
Atleta * atl = (Atleta*) malloc(count * sizeof(Atleta));
for (i=0; i<count; i++){
int nr = fscanf(fp, "%s%s%d%d%d",atl[i].cod, atl[i].nome, &atl[i].tN, &atl[i].tB, &atl[i].tC);
//just controlling if the reading is done properly
if (nr < 4) {
printf ("cannot read the file %s",fileName);
exit (1);
}
} fclose(fp);
return atl;
}
I then use this function in this main
int main (){ int dim; Atleta * a; int i;
a = leggiRisultati("risultati.txt", &dim);
for (i =0; i<dim;i++){
stampaRisultato(a[i]);}
return 0;
}
Where "stampaRisultato" prints a line of the file just read and "Atleta" is a struct defined as:
typedef struct {
char cod[5];
char nome[21];
int tN, tB, tC;
}Atleta;
And last, yes the text file is in the same directory as my executable, yes I have the permission to open the file, the file contains a certain number of lines with 2 strings and 3 int each.
Your code should work, I can only think of 3 things that may cause this issue.
In my experience, it's oftentimes the simplist mistakes that get you, because you're so focused on the more complex elements that some things slip your mind. I can't see the rest of your program, so forgive me if any of these answers seem patronizing. Here are the first things I would check:
1.) file permissions. Make sure you're a user with permission to access and/or change the file in question. This is a pretty easy fix on linux, but I don't know about windows.
2.) file location. Make sure your text file is in the same directory as your executable. You'll need to do this if you don't specify file location.
3.) #include statements. Sometimes even the best of us get too excited to get into the bulk of our program, and we forget to include stdio.h and/or stdlib.h. If this is the case you may run into an issue where you set the file pointer to null, and then the fopen function doesn't run, so your pointer remains null.
Right, I've got this code:
if(argc>1){
FILE * pFile = fopen(argv[1],"rb");
perror("");
}else{
FILE * pFile = fopen("hardcoded","rb");
}
if(pFile==NULL){
puts("Unable to open source file");
return -1;
}
However, I get this weird output:
Success
Unable to open source file
Weirdlier, if I do this:
if(argc>1){
FILE * pFile = fopen(argv[1],"rb");
perror("");
}else{
FILE * pFile = fopen("hardcoded","rb");
}
FILE * pFile = fopen("hardcoded","rb");
if(pFile==NULL){
puts("Unable to open source file");
return -1;
}
Where hardcoded exists, it all works fine!
What the blazes does that mean?
Compiling with GCC4 on Ubuntu
I'm surprised your code compiles, since the you are declaring FILE *pFile scoped to the if and the else blocks. If you've declare it prior to that, then remove the FILE* text in front of the assignments in the if/else blocks.
Don't define pFile within the if statement, you're losing scope.
FILE * pFile;
if(argc>1){
pFile = fopen(argv[1],"rb");
perror("");
}
I'd bet you've got a FILE * pfile; earlier in your code that you didn't include. If it's outside all blocks, and has static storage duration, it's initialized to NULL.
When you then have FILE * pfile = fopen(... in an inner block, the two pfiles are two different things. Therefore, what's happening:
You're defining pfile in a block, and opening it fine. Then you reach the end of the block, and it's being discarded like any other variable local in a block.
You're left with the original pfile, which you never opened or assigned anything to, and that's likely to be NULL.
In the second case, you're opening a file and discarding it, and then you have a FILE * pfile in the same scope as the testing if statement, and that's the one you're testing, so it's fine.
What you need to do is define pfile only once, since additional definitions will either cause compiler errors or give you separate versions. Take all the FILE * out of your inner blocks, and just use the same pfile all the time.
Just a quick question: Is there a way to duplicate a file pointer (those returned by fopen()), similar to how dup() duplicates a file handlers returned by functions like open()?
Basically, I want to be able to do something like this:
FILE *fp = fopen("some_file", "r");
FILE *fp2 = /* do something to duplicate the file pointer */;
fclose(fp); // fp2 is still open
/* do something with fp2 */
fclose(fp2);
FILE *fp2 = fdopen (dup (fileno (fp)), "r");
You could use fileno to get a descriptor for a FILE*, dup that, and then use fdopen to get a new FILE* from the new descriptor.
I opened twice the same file and assigned two pointers and in the end closed both separately. In my case I had to show the content in a text window using one pointer and process the data in file using the other pointer.
e.g.
//define global variables
FILE *fp1 = fopen("some_file", "r");
//fp1 used in functioncall to display textbuffer
fclose(fp1);
//fp2 used in functioncall to process data
fclose(fp2);