|
-
February 25th, 2012, 11:04 PM
#5
Re: Segmentation fault and also bad initalization
Ok, so I set the value of s just to see what happens. Still getting the segmentation fault. Is it my value of fp? I've no way to tell as when I tried to print out its value, I got like $ and weird blurs or something. Probably because fp is a pointer, but I even tried dereferencing it and it still showed those weird symbols. What's going wrong?
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(int argc, const char* argv[])
{
char* s = "Empty";
if (argc !=3)
{
printf("You're forgetting some of the arguments.");
exit(1);
}
char read_msg[BUFFER_SIZE];
int fd[2];
pid_t pid;
FILE *fp;
FILE *fp2;
fp = fopen(argv[2], "r");
if(!fp){
fprintf(stderr, "File - %s - could not be opened.\n", FILEPATH);
return -1;
}
printf(s);
exit(1);
s = fgets(s, strlen(s), fp); //ERROR HERE!!!
/* create the pipe */
if (pipe(fd) == -1){
fprintf(stderr, "Pipe failed");
return 1;
}
char write_msg[BUFFER_SIZE] = "Testing"; //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, strlen(read_msg), 1, fp2);
/* close the write end of the pipe */
close(fd[READ_END]);
fclose(fp2);
}
return 0;
}
Right now it is set to exit before it hits the segmentation fault.
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
|