Jump to content

Beginner's help

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
blacksaibot

blacksaibot

    Newbie

  • Members
  • Pip
  • 2 posts
I am new to C, literally. My lovely professor wants us to teach ourselves to program while he compiles it and tells us we're wrong without going into any details. If it compiles and it runs = A, if it doesn't = F. There's no inbetween. By the way, this is to be compiled using "gcc" in an UNIX environment

part a:
First of all, you are supposed to write a program in either C or C++ that reads data from a file and copies it to another file. Your program should copy all contents of the file.

part b:
Secondly, write another program to create child processes from your main program recursively using fork( ) and exec( ) commands up to a certain level, for example, fifth level. Then print identification of each child process in each level.


My code:

Part A:Code:
#include<stdio.h>
#include <string.h>

int main(void)
{
// open a text file for reading
FILE *in_file
in_file = fopen("input.txt","r");

// open a text file for writing
FILE *out_file
out_file = fopen("output.txt","w");


if(!f)
{ return 1; }

while(fgets(s,80,in_file) != NULL)
{ 
//write to file
fprintf(out_file, "%s",s");
fprintf(out_file, "\n");
}

fclose(in_file);
fclose(out_file);
system("pause");
return 0; 
}
Part B:Code:
#include <stdio.h> 
#include <unistd.h>

int main()
{
/* call the recursive function */
recurse(5);
}


void recurse(int count)
{
Pid_t pid;
pid = fork(); 

if(pid < 0)
{
/* if the fork failed give error */
fprintf(stderr, "Fork Failed");
exit(-1);
}

else if (pid == 0) 
{ 
/* child process and print the ID*/
execlp("/bin/ls", "ls", NULL);
printf("Child Process ID: " + pid);
}

else 
{ 
/* parent process */
/* parent will wait for the child to complete */
wait (NULL);
exit(0);
}


/* if the count is less than one, we're finished */
if(count > 1)
{ 
exit(0); 
}

/* decrement count and call itself (recursion) */
else
{
count = count - 1;
recurse(count - 1)
}
}
Please helpe me?!!?! What am I doing wrong? What am I missing? This guy told me it'd be easy because I "know" Java and it isn't. I honestly think learning Ada was a lot easier than C.

Edited by WingedPanther, 24 March 2008 - 07:51 AM.
add code tags


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Are you getting error messages when you try to compile? If so what?
Is it compiling but not running properly?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
nutario

nutario

    Newbie

  • Members
  • PipPip
  • 23 posts
In Part A:
There are some ";" missing. (e.g FILE * in_file; )

I don't see the sence of this code part:
if(!f)
{ return 1; }
For me it is like that: You didn't declare "f".


For part B:
I only can repeat what WingedPanther said.