c - 无法使用c打开文件

标签 c file fopen unix-socket

我创建了一个函数,它使用 unix 的重定向运算符过滤数据文件中的数据并将其打印到另一个文件 下面是函数

void getdetailbyparam(char *name,char *type,int maxprice,int minprice)
{
    printf("NAME:%s\nTYPE:%s\nMAX PRICE:%d MIN PRICE:%d\n",name,type,maxprice,minprice);
    char getdetailbyparamfilelocation[1024];
    snprintf(getdetailbyparamfilelocation, sizeof(getdetailbyparamfilelocation), "\"%s/getdetailbyparam.txt\"",cwd);
    char command[1024];
    snprintf(command, sizeof(command),"awk -F['|'] '{if (($3 ~ /.*%s.*/) && ($5==\"%s\") && ($7 >= %d) && ($7 <= %d)) print $7,$3,$1}' OFS=\" | \" %s | sort -n > %s",name,type,minprice,maxprice,databasefilelocation,getdetailbyparamfilelocation);
    printf("Command is : %s\n",command);
    system(command);
    printf("File %s created\n",getdetailbyparamfilelocation);
}

只需要在“getdetailbyparamfilelocation”和“databasefilelocation”中给出路径。

现在,当我调用此函数时,文件已创建,但是当我在调用该函数后尝试打开此文件时,出现“没有这样的文件或目录”的错误 请看下面的代码

void funct(int sock)
{
    char getdetailbyparamfilelocation[1024];
    snprintf(getdetailbyparamfilelocation, sizeof(getdetailbyparamfilelocation), "\"%s/getdetailbyparam.txt\"",cwd);
    size_t len = 0;
    ssize_t read;
    FILE *fp;
    printf("Start sending data from the file at %s\n",getdetailbyparamfilelocation);
        char *line = NULL;
        fp = fopen(getdetailbyparamfilelocation, "r");
        printf("Reading file \n");
        if(fp == NULL)
        {
            perror("Error");
            exit(1);
        }
        while((read = getline(&line, &len, fp)) != -1)
        {
            char sendline[1024];
            int retu;
            snprintf(sendline, sizeof(sendline), line);
            printf("SERVER SENDING :%s\n",sendline);
            retu = send(sock, line, strlen(line), 0);
        }
} 

基本上我正在编写一个客户端服务器系统,其中服务器读取过滤结果并将它们发送到客户端以显示在客户端的终端上 请帮忙,如果需要任何进一步的信息,也请告诉我

最佳答案

只有将文件名传递给 shell 时,才需要将文件名用双引号引起来。将文件名传递给 fopen 时不需要它们。

代替

snprintf(getdetailbyparamfilelocation,
         sizeof(getdetailbyparamfilelocation),
         "\"%s/getdetailbyparam.txt\"",cwd);

使用

snprintf(getdetailbyparamfilelocation,
         sizeof(getdetailbyparamfilelocation),
         "%s/getdetailbyparam.txt",cwd);

关于c - 无法使用c打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793657/

相关文章:

c - 指向存储数据的结构体

c - 与严格别名相关的有效类型规则

c - 按值返回堆栈分配的结构是否安全?

java - JFileChooser 的 FileFilter 存在编译错误

c - fscanf 从文本文件读取二维 double 组时出现问题

C fopen模式参数

c++ - 通过引用传递参数到底是什么?

紧凑访问嵌套结构中的变量

android - 你如何覆盖而不是附加到 Android 中的文本文件?

c - 使用 fopen(arg[1] ,"r") 和 fgets() 时,输出保存为字符串还是数组?