hey guys,
im working on a little program that would ask the user to input file name and would ask the user again to specify the output file so the contents of file one would be transferred in to the file 2.
i have been working on it for few hours and it doesnt work i hope you could show me something that would make this work
thanks in advance

this is what i got so far this does what i want but this eems to me to complicated because some bits i dont understand. i im thinking this could be simplified hopefully

#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>


void getfname(char *line);

int main(void)
{
  
  char fInput[PATH_MAX];
  char fOutput[PATH_MAX];
  //  char buffer[65];
  int fd, fd2;
  char ans;
  printf("input file:  ");
  getfname(fInput);
  printf("output file: ");
  getfname(fOutput);

  
  
  if((fd = open(fInput, O_RDONLY)) < 0)
    {
      perror(fInput);
      exit(1);
    }
  
  
  if((fd2 = open(fOutput, O_WRONLY|O_CREAT, 0666)) < 0)
    {
      perror(fOutput);
      close(fd);
      exit(1);
    }
  
  // read(fd, buffer, 64);
  dup2(fd, 0);
  dup2(fd2, 1);
  
  //  printf("%d is val of fd2\n\n", fd2);
  //  printf("Here is the copy:\n");
  execl("/bin/cat", "cat", NULL);
  perror("cat");  
  // printf("%s", buffer);  
	
}

void getfname(char *line)
{
  char *np;

  fgets(line, PATH_MAX, stdin);

  np = strchr(line, '\n');

  if(np != NULL)
      *np = '\0';
  
}

Try changing this line

fgets(line, PATH_MAX, stdin);

to

fscanf(stdin, "%s", line);

Will your program open the files now?

Edited 6 Years Ago by gerard4143: n/a

Here's a simple hint on code writing...Get one piece working before you move onto the next piece of code...Your code has all the characteristics of someone guessing at the answers

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

void getfname(char *line);

int main(void)
{
	char fInput[256];
	char fOutput[256];

	int fd, fd2;
	printf("input file:  ");
	getfname(fInput);
	printf("output file: ");
	getfname(fOutput);


	if((fd = open(fInput, O_RDONLY)) < 0)
	{
		perror(fInput);
		exit(1);
	}


	if((fd2 = open(fOutput, O_WRONLY|O_CREAT, 0666)) < 0)
	{
		perror(fOutput);
		close(fd);
		exit(1);
	}

	exit(EXIT_SUCCESS);
}
void getfname(char *line)
{
	fscanf(stdin, "%s", line); 
}

Very important - Do you know why this works now?

Edited 6 Years Ago by gerard4143: n/a

oh this is much better i can actually fully understand what is going on thanks for this code and yes most of the coding i pretty much guest cos i am very not confident with c programming yet
thanks again

This question has already been answered. Start a new discussion instead.