Home > Mobile >  C program hangs after creating file
C program hangs after creating file

Time:01-09

I'm doing an exercise for University, which asks:

Create a C program called 'split', which accepts a file, and a number. The program will divide the input file in two files, one called 'part1.txt' which will contain the first n bytes, and one called 'part2.txt' which will contain the other bytes. If the input file contains less than n bytes, the file 'part2.txt' will not be created.

This is my program. What happens when I execute it, is that it creates the part1.txt file (without anything written in it) and the program hangs. I've been looking at this for a day, but can't spot the problem. Any help?

I've compiled using:

gcc -o split split.c

When i execute it, i write:

./split text.txt 10

Where 'text.txt' is a text file containing words i accurately typed by pressing random buttons on my keyboard.

int splitter;
int fd, fd1, fd2;
char buffer[5000];

int main(int argc, char** argv){

if(argc<2){
  printf("Insert 2 arguments.");
  exit(1);
}

splitter = atoi(argv[2]);

if (fd=open(argv[1], O_RDONLY) < 0){
  perror("Error\n");
  exit(1);
} else {
  if (fd1=open("part1.txt", O_RDWR | O_CREAT, S_IRWXU) <0){
    perror("Error");
    exit(1);
  }
  if(read(fd,buffer,splitter) == splitter){
    write(fd1,buffer,splitter);
    if (fd2=open("part2.txt", O_RDWR | O_CREAT, S_IRWXU)<0){
      perror("Errore");
      exit(1);
    };
    while (read(fd,buffer,1) ==1){
      write(fd2,buffer,1);
    }
    close(fd1);
    close(fd2);
  } else {
    while (read(fd,buffer,1) ==1){
      write(fd1,buffer,1);
    }
    close(fd1);
  }
  close(fd);
}

CodePudding user response:

The relational operators reside at the 6th level of C's precedence table, much higher than the assignment operators.

This statement:

if (fd=open(argv[1], O_RDONLY) < 0)

is equivalent to:

if (fd = (open(argv[1], O_RDONLY) < 0))

The < operator returns either 1 or 0, or in other words, true or false, which gets assigned to fd.

Change it to:

if ((fd = open(argv[1], O_RDONLY)) < 0)

You have the same issue in the subsequent if statement.


From Expert C Programming:

Some authorities recommend that there are only two precedence levels to remember in C: multiplication and division come before addition and subtraction. Everything else should be in parentheses. We think that's excellent advice.

  •  Tags:  
  • c
  • Related