gpt4 book ai didi

c - 如何连接两个字符数组以在 C 中从 fopen 打开文件?

转载 作者:太空宇宙 更新时间:2023-11-04 11:01:21 25 4
gpt4 key购买 nike

我在使用 c 中的“fopen”动态打开文件时遇到问题。以下代码连接两个数组,它可以正常打开文件。

char path[50] = "/boot/config-";
char kernel[50] = "3.16.3";
strcat(path, kernel);
FILE *infile = fopen(path, "r"); //file opening successfully
if(infile == NULL){printf("failed to open file");}

但是,当我尝试动态填充内核数组并将其与路径数组连接时,它无法打开文件。

char path[50] = "/boot/config-";
char kernel[50] = "";

FILE *fp = popen("uname -r", "r");//executing command for kernel version 3.16.3

if (fp != NULL){
while (fgets(kernel, sizeof(kernel)-1, fp) != NULL) {
printf("%s", kernel);//print 3.16.3
}
strcat(path,kernel);
}

FILE *infile = fopen(path, "r"); //failed to open file
if(infile == NULL){printf("failed to open file");}

最佳答案

fgets 包括换行符。有时很难注意到这就是为什么我通常将此打印用于单一测试目的,您可以准确地查看是否有奇怪的字符换行等。

printf("|%s|", path)

解决这个问题的最简单方法就是:

unsigned int strlength = strlen(path);
if (path[strlength - 1] == '\n') {
path[strlength - 1] = '\0';
}

关于c - 如何连接两个字符数组以在 C 中从 fopen 打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26939334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com