Search code examples
cfilefopenunix-socket

Unable to open file using c


I have created one function which filters data from a data file and prints it to another file using redirection operator of unix below is the function

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);
}

Just need to give paths in "getdetailbyparamfilelocation" and "databasefilelocation".

Now When I call this function the file is created but when I try to open this file after calling the function it is giving me error of "No such file or directory" Please see the following code

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);
        }
} 

Basically I am coding a client server sytem in which server reads the filtered results and send them to client to displays on client's terminal Please help and also let me know if any further information is required


Solution

  • You need the double quotes around the file name only if you pass it to the shell. You don't need them when passing the file name to fopen.

    Instead of

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

    Use

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