ItecKid
February 13th, 2012, 07:30 AM
Wracking my brain on this one. I have a C code like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ch_read (char *foo)
{
if (read(0, foo, 1) != 1) {
return -1;
}
else {
return 1;
}
}
int ch_write (char foo)
{
if (write(1, &foo, 1) != 1) {
return -1;
}
else {
return 1;
}
}
int write_help (char *msg, int len) {
int i = 0;
int flag = 0;
for (; i < len; i++) {
flag = ch_write (msg[i]);
if (flag == -1) {
fprintf (stderr, "Error writing byte!");
return -1;
}
}
return len;
}
int read_help (char *msg, int len) {
int i = 0;
int flag = 0;
for (; i < len; i++) {
flag = ch_read (&msg[i]);
if (flag == -1) {
fprintf (stderr, "Error reading byte!");
return -1;
}
}
return len;
}
int main (int argc, char *argv[])
{
char *msg = (char *)malloc(100);
if (argc != 2) {
read_help (msg, 24);
printf ("%s\n", msg);
}
else {
strcpy (msg, argv[1]);
write_help (msg, strlen(msg));
}
return EXIT_SUCCESS;
}
The code is run by using shell pipe to take use the output when an argument is passed as input to itself. So, it would be run like:
./a.out aString | ./a.out
My question is, what is the proper way to call ch_read from the read_help my function? My current implementation produces a seg fault. I have a similar example working with integers, so I know the logic is correct, just not sure what is the correct value to pass to ch_read.
Any help is greatly appreciated. This code is part of a larger design, and I am not allowed to modify any part of main, ch_read, or ch_write.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ch_read (char *foo)
{
if (read(0, foo, 1) != 1) {
return -1;
}
else {
return 1;
}
}
int ch_write (char foo)
{
if (write(1, &foo, 1) != 1) {
return -1;
}
else {
return 1;
}
}
int write_help (char *msg, int len) {
int i = 0;
int flag = 0;
for (; i < len; i++) {
flag = ch_write (msg[i]);
if (flag == -1) {
fprintf (stderr, "Error writing byte!");
return -1;
}
}
return len;
}
int read_help (char *msg, int len) {
int i = 0;
int flag = 0;
for (; i < len; i++) {
flag = ch_read (&msg[i]);
if (flag == -1) {
fprintf (stderr, "Error reading byte!");
return -1;
}
}
return len;
}
int main (int argc, char *argv[])
{
char *msg = (char *)malloc(100);
if (argc != 2) {
read_help (msg, 24);
printf ("%s\n", msg);
}
else {
strcpy (msg, argv[1]);
write_help (msg, strlen(msg));
}
return EXIT_SUCCESS;
}
The code is run by using shell pipe to take use the output when an argument is passed as input to itself. So, it would be run like:
./a.out aString | ./a.out
My question is, what is the proper way to call ch_read from the read_help my function? My current implementation produces a seg fault. I have a similar example working with integers, so I know the logic is correct, just not sure what is the correct value to pass to ch_read.
Any help is greatly appreciated. This code is part of a larger design, and I am not allowed to modify any part of main, ch_read, or ch_write.