简体   繁体   English

C:更改为argc和argv

[英]C: change into argc and argv

I'm working on a C program with some system calls and I'm saving variables as follows: 我正在使用一些系统调用来处理C程序,并且按如下方式保存变量:

int inhandle,outhandle,bytes,read_while_writing_nhandle;
char source[128],target[128];

Right now my program prompts the user with 现在我的程序提示用户

printf("enter source file name\n"); 
scanf("%s",source);

How can I change it so a user can just type "run sourceName targetName" aka, storing them as argv[1] and argv[2] ? 如何更改它,以便用户可以再次键入“ run sourceName targetName”,将它们存储为argv [1]和argv [2]

I also use the inputs (target and source) in handles like: 我还在句柄中使用输入(目标和源):

inhandle=open(source,O_RDONLY);

My main issue is conversion since I'm storing target and source as char. 我的主要问题是转换,因为我将目标和源存储为char。 I could use something like strcpy. 我可以使用诸如strcpy之类的东西。 It would just be very much appreciated if someone could help me out with it. 如果有人可以帮助我,将不胜感激。 Hope this was clear. 希望这很清楚。 Thank you. 谢谢。

** * ** * ** *EDIT: I apologize, I probably wasn't clear enough... ** * ** * ** *编辑:对不起,我可能不够清楚...

I tried doing the int main(int argc, char *argv[]) and then including: 我尝试做int main(int argc,char * argv []),然后包括:

if(argc==3) 
{ source = argv[1]; target = argv[2]; } 
else{ printf("Syntax error.\n"); 
return -1; 

But I'd get conversion errors since I can't store them that way. 但是我会遇到转换错误,因为我不能那样存储它们。 And if I do store them as pointers (like *target=argv[2]) I'm worried they won't work when I call the handles.. (ex: outhandle=open(target...) works but I can't do open(*target..) 而且,如果我确实将它们存储为指针(例如* target = argv [2]),我担心它们在调用句柄时将无法工作。(例如:outhandle = open(target ...)有效,但是我可以不要打开(*目标..)

Use int main(int argc, char **argv); 使用int main(int argc,char ** argv); And then assign source to argv[1] and target to argv[2] 然后将源分配给argv [1],将目标分配给argv [2]

Change to: 改成:

if(argc==3) 
{
    strcpy(source, argv[1]);
    strcpy(target, argv[2]);
}

Also, read up on the dangers of strcpy , and consider strncpy . 另外,请阅读strcpy的危险,并考虑使用strncpy
But using strcpy will get you started at least... 但是使用strcpy至少可以让您入门...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM