Variable Substitution in C - 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");

Related

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.

How can I refer to a file as the stream for fgets()?

fgets() returns a string from a provided stream. One is stdin, which is the user input from the terminal. I know how to do this, but if I am using compiled c code in applications, this is not very useful. It would be more useful if I could get a string from a file. That would be cool. Apparently, there is some way to provide a text file as the stream. Suppose I have the following code:
#include <stdio.h>
int main(int argc, const char *argv){
char *TextFromFile[16];
fgets(TextFromFile, 16, /*stream that refers to txt file*/);
printf("%s\n", TextFromFile);
return 0;
}
Suppose there is a text file in the same directory as the c file. How can I make the printf() function print the contents of the text file?
Given the following is defined;
char *TextFromFile[16];
char TextFromFile[16]; //note "*" has been removed
const char fileSpecToSource[] = {"some path location\\someFileName.txt"};//Windows
const char fileSpecToSource[] = {"some path location/someFileName.txt"};//Linux
From within a function, the statement:
FILE *fp = fopen(fileSpecToSource, "r");//file location is local to source directory.
if successful (i.e. fp != NULL), fp can be used as the stream argument in:
fgets(TextFromFile, 16, fp);
Later I found out the problem. fopen is stupid. Using ./file.txt or others will not work. I need to use the whole file path to do it.
FILE (*File) = fopen("/home/asadefa/Desktop/txt.txt", "r");
char FData[0x100];
memset(FData, '\0', 0x100);
for(z = 0; z < 0x100; ++z) {
fgets(FData, 0x100, File);
}
fclose(File);
I should have noted that the full file path is used.

Specify file extension

Right now, what I have is this:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char fname[100];
FILE* fp;
memset(fname, 0, 100);
/* ask user for the name of the file */
printf("enter file name: ");
gets(fname);
fp = fopen(fname, "w");
/* Checks if the file us unable to be opened, then it shows the
error message */
if (fp == NULL)
printf("\nError, Unable to open the file for reading\n");
else
printf("hello");
getch();
}
This functions just fine, but is there a way I can force it to save as a .txt or a .data or something? Right now it just saves as the name you put in with no extension. Other than asking the user to just input the name and extension, I can't think of a way to do that. I mean, it still works just fine for reading/writing purposes, I just think an extension would be nice.
to expand my comment:
strcat(fname, ".txt");
The strcat function can be used to append text to a destination buffer, assuming the destination is large enough to store the new text.
char *strcat(char *destination, const char *source);
The source is the new text that you want to append (in your case the extension), and the destination is where the new text will be added. If destination is not big enough, then the behavior is undefined.
One could also use the snprintf function to append text, which is safer, as it takes a size argument.
I figured it out. Credit goes to a friend of mine who showed this to me earlier today.
int main()
{
FILE *Fileptr;
char filename[50];
char file[50];
int c;
printf("What do you want to name your file?");
scanf("%s", filename);
sprintf(file, "%s.txt", filename);
Fileptr = fopen(file, "w");
fprintf(Fileptr, "Data goes here");
fclose(Fileptr);
return 0;
}
Much easier than what I had been doing.

How to write file inside folder in current directory using fopen

I want to write to a file, that is inside a folder in the current working directory, with the file name being the number value that is passed to the function.
void record_data(number[]) {
FILE *fptr;
fptr = fopen("./folder/number", "w");
}
I'm unable to do so in this way (it names the file as number).
How can I do this properly?
Assuming you meant int number as opposed to your number[] which is not valid C.
You can use sprintf(), or preferably snprintf():
void record_data(int number) {
char str[255]; //Large enough buffer.
snprintf(str, sizeof(str), "./folder/%d", number);
FILE *fptr;
fptr = fopen(str, "w");
}
And consider calling fclose() on your FILE * when you're done using it.

fgets() not working.in C?

Edit: Deleted all but the main question.
My program here is supposed to create a file at a specified directory, and write specified text to it. A correct file's path and content should look something like this:
Path: D:\test.txt
Content: The printing succeeded.
For some reason, my code won't recognize the "path" variable. I don't know what I'm doing wrong here. The "text" variable works fine.
#include<stdio.h>
int main()
{
//Declaring variables
char path[999];
char text[999];
FILE *fp;
//prompting for path variable
printf("Specify a file path.\n");
fgets(path,999,stdin);
printf(path);
//prompting for the text variable.
printf("What do you want to write?");
fgets(text,999,stdin);
printf(text);
//opening and printing to file.
//fp = fopen("D:\\test.txt", "w");
fp = fopen(path, "w");
fprintf(fp, text);
fclose(fp);
//test print to see that the program completed correctly.
printf("\nThe printing has been done.");
return 0;
}
The thing I don't understand is that fp = fopen("D:\\test.txt", "w"); works, but fp = fopen(path, "w"); doesn't. I've tried putting in these different paths.:
D:\\test.txt
D:\test.txt
D\test.txt
D\\test.txt
It doesn't open the file when you open the variable path because fgets() reads the newline and puts it at the end of the string (if there's enough space in the buffer). In order to make it work you have to manually remove the newline from the string.
Try this before opening the file.
if(isspace(path[strlen(path)-1]))
path[strlen(path)-1]='\0';
You might also need to include <ctype.h>

Resources