LewisFletch
LewisFletch

Reputation: 125

open and write file function / passing a variable to the function in c?

Because i'm using the function of opening, reading and writing a file a lot i have the following

#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include "header.h"
#include <fcntl.h>
#include <string.h>


int openfile()
{
char buffer[4096];
int input_file1;
char userInput = malloc(100);
int n;

if((input_file1 = open(userInput, O_RDONLY)) < 0) //opens file specified as userInput
{
    perror(userInput);
    exit(1);
}

while((n = read(input_file1, buffer, sizeof(buffer))) > 0) //reads file
{
    if((write(STDOUT_FILENO, buffer, n)) < 0) //writes to stdout
    {
        perror("failed to display file to output");
        close(input_file1);
        exit(1);
    }
}

}

Obviously the variable userInput is not set but i want to be able to...call this function in main(); multiple times for potentially different userinputs.

how do i take a variable that is set in main(); and pipe it into the below function?

so, in main(); i'd call openfile(); AFTER receiving an input that sets the userInput variable and then openfile(); would write the file that was requested.

just looking to be pointed in the right direction, the answer is probably quite simple.

thanks

Upvotes: 0

Views: 158

Answers (1)

P.P
P.P

Reputation: 121387

You can't "pipe" a value to a function in C (like unix pipe). However, you can simply pass the userInput to your function openfile().

int openfile( char *userInput)
{
 char buffer[4096];
 int input_file1;
 int n;
 .....
}

and pass it from main():

int main(void)
{
char userInput[256];

/*read userInput here */   
openfile(userInput);   
....
return 0;
}

You could use a loop if you want to read multiple inputs and print them all.

int main(void)
{
int i;
char userInput[256];

for (i=0; i<10; i++)  { /* Reads 10 files */
  /*read userInput here */   
  openfile(userInput);   
}
....
return 0;
}

Upvotes: 1

Related Questions