簡體   English   中英

將字符串作為參數傳遞給 function,然后使用該字符串值在 C 中打開文件

[英]Passing a string as an argument to a function, then use that string value to open a file In C

假設我有兩種方法: int main(void)void func(char *FileName)

main方法將掃描用戶的文件名,然后將值保存到char fileInput[20] ,然后調用func(fileInput)

func方法中,我想打開一個文件FILE *infile = fopen(/*FileName as string value*/, "rb"); ,但使用參數值作為要打開的文件名。

void func(char *FileName){
    //Open the file.        
    //FileName = address of first element of char array
    //*FileName = value of first element of char array
    //But How can I use the all the elements of the char array as a string ?
    FILE *infile = fopen(/*FileName as string value*/, "rb"); 
}

int main(void) {
    //Assuming the user will always enter a valid value.
    char fileInput[20];
    //Prompt the user to input a value.
    printf("File name then enter: ");
    //Save the input value to fileInput.
    scanf("%s", fileInput);
    func(fileInput);
}

例如,如果fileInput[20] = "hello"; , 然后調用func(fileInput);

如何使用"hello"值在func方法中打開文件?

FILE *infile = fopen(value of fileInput = "hello", "rb");

我不確定這是否是您要問的,但這是fopen()的 function 原型,

FILE *fopen(const char *pathname, const char *mode);

pathname是指向 char 的指針。 您不限於硬編碼pathname ,您可以為其提供一個變量(假設它的類型為char * )。

所以這:

FILE *infile = fopen(/*FileName as string value*/, "rb"); 

變成這樣:

FILE *infile = fopen(FileName, "rb"); /* Filename is the argument you provided by calling the function */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM