C open()为路径字符串返回-1

C open()为路径字符串返回-1,c,path,directory,system-calls,C,Path,Directory,System Calls,当我使用open()作为 它很好用 但是,当我使用字符串作为(存储在字符串中的相同路径)路径时,它不起作用 int ff=open(string,O_RDONLY); 为什么会这样 这是我的全部密码。我很困惑。我知道它应该有用。但我没有。我找不到窃听器 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys

当我使用open()作为

它很好用

但是,当我使用字符串作为(存储在字符串中的相同路径)路径时,它不起作用

int ff=open(string,O_RDONLY);
为什么会这样

这是我的全部密码。我很困惑。我知道它应该有用。但我没有。我找不到窃听器

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>

void bla(char *);
int main(void)
{
// int i;
FILE * fp=fopen("path","r");
char line[256];

while( fgets(line,255,fp)!=NULL){

bla(line);

 }

return 0;
}


void bla(char * line){

int status;
printf("%s",line);


pid_t pid=fork();

char string[256];
if(pid==0){

    pid=wait(&status);

    int ff=open(line,O_RDONLY);

    if(ff<0){
        printf("\topen error!\n\n");
    return;}

    int ret=read(ff,string,255);

    if(ret<0){
        printf("read error!\n");
    return;}

    printf("%s",string);
close(ff);

exit(0);


}   
if (pid>0){
        return;
}
 }
#包括
#包括
#包括
#包括
#包括
#包括
#包括
无效bla(字符*);
内部主(空)
{
//int i;
文件*fp=fopen(“路径”,“r”);
字符行[256];
while(fgets(第255行,fp)!=NULL){
bla(线路);
}
返回0;
}
无效bla(字符*行){
智力状态;
printf(“%s”,第行);
pid_t pid=fork();
字符串[256];
如果(pid==0){
pid=等待(&状态);
int ff=开路(仅限线路);
如果(ff我称之为恶作剧:-)

显然,如果
string
的值与字符串文本的值完全相同,并且所有其他内容都保持不变,那么它就可以正常工作

因此,如果所有其他东西都相同,
string
显然没有设置为您认为的值,即
“/home/user/desktop/bla/test”

我的建议是打印出来(连同一个错误字符串),例如:

fprintf (stderr, "DEBUG: string is [%s]\n", string);
int ff = open (string, O_RDONLY);
if (ff < 0)
    perror ("Could not open file");
while (fgets (line, 255, fp) != NULL) {
    size_t ln = strlen (line);             // Add these
    if ((ln > 0) && (line[ln-1] == '\n'))  //   three
        line[ln-1] = '\0';                 //   lines.
    bla (line);
}
然后推导出问题

解决此问题的一个快速方法是自己删除换行符,方法如下:

fprintf (stderr, "DEBUG: string is [%s]\n", string);
int ff = open (string, O_RDONLY);
if (ff < 0)
    perror ("Could not open file");
while (fgets (line, 255, fp) != NULL) {
    size_t ln = strlen (line);             // Add these
    if ((ln > 0) && (line[ln-1] == '\n'))  //   three
        line[ln-1] = '\0';                 //   lines.
    bla (line);
}

您还可以演示“字符串”是如何定义和初始化的吗?也许:char*string=“/home/user/desktop/bla/test”?请尝试使用
strerror
@udakarajd打印
errno
,谢谢您发布代码。问题在于
fgets
保留了尾随的换行。请参阅更新的答案。