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
Related
I am a beginner at C and am using DevC++. I have written the code below and wish to read in the data written in input.txt. However when I try to run the code, I always receive the "Cant open file" message. It seems unable to find input.txt, and I am entirely unsure how to change that.
int T;
char command;
FILE *inputfile;
inputfile = fopen("input.txt", "r");
if(inputfile == NULL)
{
printf("Cant open file");
}
fscanf(inputfile, "%d", &T);
It can be because of the following reasons
File you are reading and your source code are not in same directory
You have misspelled the file name
Otherwise your code is correct there should be no problem
I am new to C, I am just trying to read a simple text file I created in C. I made this file by clicking new -> empty file -> saving it to my desired location and then adding the file extension (.txt) the text file holds a sample sudoku board and the full file name is sudokuchar.txt.
The code I have to read from the file and print it is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpointer = fopen("sudokuchar.txt", "r");
char input[100];
while(fgets(input,100,fpointer))
{
printf("%s",input);
}
fclose(fpointer);
}
so when i compile the program does not print anything and returns -1. I assume something is wrong with the file i am trying to read from?? if some one could help it would be greatly appreciated.
Always check the return values of fopen and other standard library calls. It's most likely that your file doesn't exist. You can make a nice user friendly error message using errno, just make sure to include errno.h. Overall, your code should work, but you NEED to check the return values of things, because fopen returns NULL if it can't find the file.
FILE *fpointer = fopen("sudokuchar.txt", "r");
if(fpointer == NULL) {
fprintf(stderr, "Error: [Errno %d]: %s\n",
errno, strerror(errno));
return 1;
}
It is advisable to check what file pointer returns. If file pointer returns 0 or NULL then File pointer is unable to point to the file name you had provided. Also you can use this
File *fp = fopen(file name with full path (i.e. /home/chex/read.txt),"r")
Check man fopen
FILE *fopen(const char *path, const char *mode);
I want to open a file, read its contents, and then append a line to the file. I thought I should use the "a+" flag for the task.
I have a function which opens a file and returns a pointer to this file.
FILE* open_weekly_disk_file(char* filename){
FILE* weekly_log;
weekly_log = fopen(filename, "a+");
//weekly_log = fopen(filename, "r");
if(! weekly_log){
printf("The attempt to open the weekly log failed!\n");
return NULL;
} else{
return weekly_log;
}
}
Then I have a function which calls the function above and uses scanf to read contents from the file:
void sample_function(char* filename){
FILE* log;
char token[100], current_read[100];
int limit;
log = opened_weekly_disk_file(filename);
// The problem happens here
for(limit=0; limit < TOKEN_NUMBER; limit++){
if(fscanf(log, "%s%s", &token, ¤t_read) == 2){
printf("%s %s\n", token, current_read);
}
}
...
}
This code works when I use:
weekly_log = fopen(filename, "r");
But does not work when I change the "r" flag to "a+". I get a Segmentation fault right before the for loop.
That is because the mode spec "a" opens a file for appending, with the file pointer at the end. If you try to read from here, there is no data since the file pointer is at EOF. You should open with "r+" for reading and writing. If you read the whole file before writing, then the file pointer will be correctly positioned to append when you write more data.
If this is not enough, please explore ftell() and fseek() functions.
from this SO QA
from the man page:
a+
Open for reading and appending (writing at end of file). The file is
created if it does not exist. The initial file position for reading is
at the beginning of the file, but output is always appended to the end
of the file.
Answer:
There is just one pointer which initially is at the start of the file
but when a write operation is attempted it is moved to the end of the
file. You can reposition it using fseek or rewind anywhere in the file
for reading, but writing operations will move it back to the end of
file.
So, the problem is not the fact that the file is opened in append mode, because it is not, as far as reading from it is concerned.
The problem lies in what your code does in those three dots
log = opened_weekly_disk_file(filename);
...
The code quite probably writes to the file, making the file cursor move to the end of it before the reading occurs.
So, I have this function on my program that is supposed to save a "car_str" structure into the desired place on a file specified as a parameter. But when I run it, it keeps overwriting the first slot again and again, as if fseek didn't point to the specified place on the file. Is there any problem with my code? I think it may be related with the multiplication, since without it the program does well, but I cannot point to the place I want.
void save(int car_nbr)
{
FILE *f;
f = fopen("memory.txt","wb");
if (!f)
{
printf ("error");
}
else
{
car_nbr--;
fseek(f, sizeof(struct car_str)*car_nbr, SEEK_SET);
fwrite(&car,sizeof(struct car_str),1,f);
rewind(f);
fclose(f);
printf("\nsaved");
}
}
you need to fopen with r+b.
if you fail than file not exist, so you can try use "wb"
"w" - write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"r+" - read/update: Open a file for update (both for input and output). The file must exist.
f = fopen("memory.txt","r+b");
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);