File name variable in file path in C - c

So I am writing a program that uses text files. I have a line of code that goes like this.
pfw = fopen(fileName, "w");
I am trying to make that program to create a txt file in this relative path
./TextFiles/
I have no idea how to implement a fileName variable in the file path.
I usually do it like this when I have static fileName and program doesn't ask me to give it a file name or where fileName is not a variable and it works.
pfw = fopen("./TextFiles/fileName.txt", "w");

#define the relative path if configuration files are not being used
#define BASE_DIR "./TextFiles/"
char* finalName = malloc (strlen(BASE_DIR) + strlen(fileName) + 1);
if (!finalName) { /* error handling */ }
sprintf (finalName, "%s%s", BASE_DIR, fileName);
FILE* pfw = fopen(finalName, "w");
/*
...
*/
// free after usage
free (finalName);

Related

Finding text file from user input in c

There are multiple .txt files in a folder like;
math.txt
physics.txt
programming.txt
User must enter lesson's name and then program should open .txt file and read it.
The problem is I can't use a variable in fopen() function.
FILE *lesson= fopen("...\\lessons\\[user input].txt","r");
any idea?
What makes you think you can't use a variable in fopen()?
Try this:
#define PATH_STRING "...\\lessons"
//Allocate enough memory for the whole filepath
char *buffer = malloc(strlen(PATH_STRING) + strlen(argv[index]) + 6);
//Write the path into the buffer
sprintf(buffer,"%s\\%s.txt", PATH_STRING, argv[index]);
//Pass the pointer to the buffer as an argument of fopen()
FILE *fp = fopen(buffer,"r");
free(buffer);

Is there a way to use fopen() to read/write a file when the file directory changes, but without manually changing the directory in the actual code?

I know how to read and write to a file, but I am including fopen() in my university project, and we are required to send everything that is required to run the program to the lecturer. But if the directory names change, is there a possibility that my program would not be able to read the file?
int main(void)
{
FILE * fptr;
fptr = fopen("C:\\Users\\username\\Documents\\folder\\filename.txt", "r");
char oneline[MAX_LEN];
while (!feof(fptr))
{
while (fgets(oneline, sizeof(oneline), fptr) != NULL)
printf("%s", oneline);
}
fclose(fptr);
return 0;
}
For example, if my professor downloads the file, and it is kept in downloads instead of documents like the directory I wrote, wouldn't the file be unable to be read? And if so, is there a way for me to make my code "adapt" to the changes in directory?
Use relative paths.
//if your executable and the textfile are in the same directory just use
fptr = fopen("filename.txt", "r");
//if e.g. your executable is in Documents use
fptr = fopen("folder//filename.txt", "r");
by the way, use ".." to get into the parent directory.
Alternatively, if you want to change the path at runtime, store it in a c string (char array / char pointer), so you can easily replace/change it by just setting the char pointer to the string you want.
char * path = "your path here";
char * someotherpath = "other path (maybe from userinput)"
// you can easily change your the path
if(some condtion)
path = someotherpath;
fptr = fopen(path, "r");
It should be detected automatically whether it is a absolute or relative path.

Get path from input to read a file

I would like to get a name of file from input and then read it. (Suppose that the file is in the directory of program.) To do that I need an absolute path. Please let me know how to achieve this goal using C.
This a part of my code:
scanf("%s",&filepath1);
FILE * fdw = fopen(filepath1, "a");
delete the '&' symbol.
char filepath1[SIZE] = {0};
scanf("%s", filepath1);
FILE * fdw = fopen(filepath1, "a");

Variable Substitution in C

I want to open a file. Easy enough. Use fopen(). However, what file to open depends on the user input. I am somewhat proficient in Korn Shell scripting and this is easily done using variable substitution: $(var). I am unable to figure out the correct format in C. Could someone please give me some insight?
My code -
#include <stdlib.h>
#include <stdio.h>
char statsA[100];
char fileA[50];
int main (void)
{
printf("Enter file to open\n");
gets(fileA);
FILE *statsA;
statsA = fopen("c:/Users/SeanA/C/***<fileA>***", "r+");
.......................................^ What goes here?
I am unsure of how to include the user input in the fopen string.
This is what sprintf is for. It works like printf, except that its output goes to a string instead of stdout.
char filename[100];
sprintf(filename, "c:/Users/SeanA/C/%s", fileA);
statsA = fopen(filename, "r+");
Also, the definition of statsA you have inside of main masks the definition at file scope. You probably want to give these different names.
You must concatenate both strings manually. Something like this
char* folder = "c:/Users/SeanA/C/";
char* path = malloc(strlen(fileA) + strlen(folder) + 1);
path = strcpy(folder);
path = strcat(fileA);
FILE *statsA = fopen(path, "r+");
free(path);//Always free your memory
Do scanf to get the file from the user.
make a char array to hold the filename.
char filename[15];
Now ask for the file name:
printf("What is the name of the file?\n");
scanf("%s", &filename);
Note: Include the FULL file name. so if I have a text doc called filename The user would need to type filename.txt
Now you have the file name you can declare a file pointer
FILE * fp;
fp = fopen(filename, "r");
Now you should be able to scan your file!
fscanf(fp, "%d", &value);
EDIT: I did not notice you wanted string concatenation with your file path.
Since you know the predefined path you can make another char array that holds that string path
char fullPath[100];
char path[75] = "c:/Users/SeanA/C/";
Now you can use strcat to bring them all together!
strcat(fullPath, path);
strcat(fullPath, filename);
Now you do fopen(fullPath, "r");

How can I get a file pointer ( FILE* ) of known file in a specific path?

to read/write a file i need file pointer in language C in Unix environment.
I know a file name and path, but how to get file pointer using its name and path.
#include <stdio.h>
FILE * pFile;
pFile = fopen ("myfile.txt","w");
Import the standard input/output header like so
#include <stdio.h>
And then create a pointer for the file you want to open.
FILE * file_pointer;
file_pointer = fopen ("[path to file]","w");
fclose(file_pointer);
NOTE: Specify whole path to file if it is not in the same directory as your source file.
Dont forget to close the file after you have done the operations you need
According to the post from ssmithstone:
#include <stdio.h>
FILE * pFile;
/* open file and check if was successful */
if ((pFile = fopen("myfile.txt", "w")) == NULL)
{
/* couldn't open file; do some error handling if u want */
}
else
{
/* do s.th. */
/* close file */
fclose(pFile);
}
In this case w means writing. For other options check the link posted by Yu Hao.
Seems like you are new in C programming, I've written a C program for you, you can analyse it and I believe it will be definitely helpful to you.
#define size 50
#include <stdio.h>
int main()
{
char name[size];
FILE *file;
file = fopen("your_file.txt","w");
printf("Please enter your first name\n");
scanf("%s",name);
fprintf(file,"%s",name);
fclose(file);
return 0;
}
Details:
In line 7 the second parameter w is used as file open mode - with write privileges.
The file pointer is used to create / open a file with name "your_file.txt".
function fprintf() is same as printf() function but it writes not on console but to your file.
finally we need to close the file writing operations thus we use fclose() function
Update:
To specify your path you can write your file path with your filename.fileextension
for example: You can write it as
file = fopen("/home/depthgr8/Desktop/your_file.txt","w");
This will create your_file.txt in given path if your path exists otherwise it will throw a runtime exception - segmentation fault (core dumped)

Resources