Skip to content
Advertisement

I read more than I write in file

I have a file, partitioned in fixed sized blocks. I am copying a test_file.txt into the 3rd block of the file. I read and copied 18 bytes.

Then I am trying to copy from the file that very same .txt file I just imported to a newly created .txt, but I am writing 256 bytes to the new file. Moreover, when I try to read it, it is full of garbage.

The first function is used to import the .txt and the second one to export it.

void copy_file(int mfs_desc, char* filename, Superblock* s, MDS mds) {
  if(mds.size == 0)
    return;
  char buffer[s->block_size];
  int i = 0;
  for (; i < s->block_size; ++i) {
    buffer[i] = '';
  }

  int source_desc = open(filename, O_RDONLY);
  // error handling
  if (source_desc == -1) {
    perror("opening file in copy file");
    exit(1);
  }

  ssize_t nread;
  int total = 0;

  off_t seek = lseek(mfs_desc,
               sizeof(Superblock) + mds.datablocks[0] * s->block_size,
               SEEK_SET);
  printf("offset = %dn", mds.datablocks[0]);
  if (seek < 0) {
    perror("seek");
    exit(1);
  }

  total = 0;
  while ((nread = read(source_desc, buffer, s->block_size)) > 0) {
    total += nread;
    write(mfs_desc, buffer, s->block_size);
  }
  printf("read and copied: %d bytesn", total);

  if (close(source_desc) == -1) {
    perror("closing file in copy file");
    exit(1);
  }
}

int copy_file_export(int mfs_desc, char* filename, Superblock s, MDS mds) {
  if(mds.size == 0) {
    printf("File is empty, abortn");
    return 0;
  }
  char buffer[s.block_size];
  int i = 0;
  for (; i < s.block_size; ++i) {
    buffer[i] = '';
  }

  int destination_desc = open(filename, O_CREAT | O_WRONLY);
  // error handling
  if (destination_desc == -1) {
    printf("filename = |%s|n", filename);
    perror("opening file in copy file export");
    exit(1);
  }

  ssize_t nread;
  int total = 0;

  off_t seek = lseek(mfs_desc,
               sizeof(Superblock) + mds.datablocks[0] * s.block_size,
               SEEK_SET);
  printf("offset = %dn", mds.datablocks[0]);
  if (seek < 0) {
    perror("seek");
    exit(1);
  }
  for(i = 0; i < mds.size; ++i) {
    nread = read(mfs_desc, buffer, s.block_size);
    total += nread;
    write(destination_desc, buffer, nread);
  }
  printf("wrote: %d bytesn", total);

  if (close(destination_desc) == -1) {
    perror("closing file in copy file");
    exit(1);
  }
  return 1;
}

Output:

import test_file.txt ... / <-- just a command
offset = 2
read and copied: 18 bytes
export test_file.txt ... ../../ <-- just a command
offset = 2
wrote: 256 bytes

What I am doing wrong?

Advertisement

Answer

I would replace

write(mfs_desc, buffer, s->block_size);

with

write(mfs_desc, buffer, nread);

Advertisement