|
-
February 25th, 2012, 10:01 PM
#1
[RESOLVED] Segmentation fault and also bad initalization
Code:
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define FILEPATH "./input.txt"
#define FILEPATH2 "./copy.txt"
#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1
int main(void)
{
char* s;
char read_msg[BUFFER_SIZE];
int fd[2];
pid_t pid;
FILE *fp;
FILE *fp2;
fp = fopen(FILEPATH, "r");
if(!fp){
fprintf(stderr, "File - %s - could not be opened.\n", FILEPATH);
return -1;
}
s = fgets(s, 32766, fp); //ERROR HERE!!!
/* create the pipe */
if (pipe(fd) == -1){
fprintf(stderr, "Pipe failed");
return 1;
}
char write_msg[BUFFER_SIZE] = s; //How do I get this value of s into the right format?
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
if (pid > 0) { /* parent process */
/* close the unused end of the pipe */
close(fd[READ_END]);
/* write to the pipe */
write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
/* close the write end of the pipe */
close(fd[WRITE_END]);
}
else { /* child process */
/* close the unused end of the pipe */
close(fd[WRITE_END]);
/* read from the pipe */
read(fd[READ_END], read_msg, BUFFER_SIZE);
// printf("read %s", read_msg);
fclose(fp);
fp2 = fopen(FILEPATH2, "w");
fwrite(read_msg, 32767, 32767, fp2);
/* close the write end of the pipe */
close(fd[READ_END]);
fclose(fp2);
}
return 0;
}
The problem is probably the fact that I'm using the variable s in the wrong way, but as I'm very bad at C and C++, at least so far anyway, I've no clue what's wrong.
Is it my size that I passed in the marked method?
Also, how do I tell it, later, once this starts to work, to pass the file name of the file it'll copy to as the first param and the file it reads from to the pipe as the second param?
I'm supposed to be reading from a file, and as I was given some help code, but it's probably in C and not C++, even if it is, I'm still not that great at C++ either, but anyway, I'm to have the program read from the file and write to the pipe and have the child read from the pipe and write to the output file.
FileCopy copy.txt input.txt
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|