C 中的变量替换 [英] Variable Substitution in C

查看:48
本文介绍了C 中的变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个文件.很容易.使用 fopen().但是,要打开的文件取决于用户输入.我有点精通 Korn Shell 脚本,这可以使用变量替换轻松完成:$(var).我无法找出 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?

我不确定如何在 fopen 字符串中包含用户输入.

I am unsure of how to include the user input in the fopen string.

推荐答案

执行 scanf 从用户那里获取文件.

Do scanf to get the file from the user.

制作一个字符数组来保存文件名.

make a char array to hold the filename.

字符文件名[15];

现在询问文件名:

printf("文件名是什么?\n");

scanf("%s", &filename);

注意:包括完整的文件名.所以如果我有一个名为 filename 的文本文档,用户需要输入 filename.txt

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

我没有注意到您想要将字符串与您的文件路径连接起来.

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

现在您可以使用 strcat 将它们组合在一起!

Now you can use strcat to bring them all together!

strcat(fullPath, path);

strcat(fullPath, filename);

现在你做 fopen(fullPath, "r");

这篇关于C 中的变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆