Variable Substitution in C

寵の児 提交于 2019-12-11 10:24:22

问题


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.


回答1:


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



回答2:


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.




回答3:


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");



来源:https://stackoverflow.com/questions/36800518/variable-substitution-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!