0

I'm using plain C and trying to read data from stream device (single tape)

size_t res=0;
size_t total=0;
char data[512];
FILE *f = fopen("/dev/st0","r");
if(!f)
{
    perror ("Error:");
    printf( "Value: %d\n", errno );
    return;
}
while((res=fread(data,1, sizeof data,f))>0)
{
    total+=res;
}
fclose(f);
printf("read: %ld bytes\n", total);

It doesn't work this way, so I assume there should be some specific way to do it.
I didn't find something useful in google. May be source code of mt tool can help, but again it doesn't read/write to tape.

The result is
read: 0 bytes

5
  • Check the return value of fopen.
    – Kninnug
    Dec 13, 2013 at 14:21
  • What is this code exactly supposed to do?
    – alk
    Dec 13, 2013 at 14:23
  • Does it work if you do cat /dev/st0 > myfile?
    – Devolus
    Dec 13, 2013 at 14:24
  • I'm sorry, I updated the post.
    – pugnator
    Dec 13, 2013 at 14:25
  • Yes, it works for cat and doesn't work for dd. As expected
    – pugnator
    Dec 13, 2013 at 14:25

1 Answer 1

3

To read the first sizeof(data) bytes (if any) from the device specified do like so:

#define _POSIX_SOURCE /* for ferror */

#include <stdio.h>

#define DEVICENAME "/dev/st0"

int main(void)
{
  int result = EXIT_SUCCESS; /* Be optimistic. */

  size_t total = 0;
  char data[1024];

  FILE * f = fopen(DEVICENAME, "r");
  if (NULL == f)
  {
    fprintf(stderr, "Failed to open '%s'.\n", DEVICENAME);
    result = EXIT_FAILURE;
  }
  else 
  {
    total = fread(data, 1, sizeof(data), f);
    if (ferror(f))
    {
      fprintf(stderr, "Error reading from '%s'.\n", DEVICENAME);
      result = EXIT_FAILURE;
    }  

    fclose(f);
  }

  printf("Read %zd bytes from '%s'.\n", total, DEVICENAME);

  return result;
}
7
  • No, removed. @Shahbaz
    – alk
    Dec 13, 2013 at 14:33
  • Probably a habbit when writing macros to carry the box with extra parenthesis along. @Shahbaz
    – alk
    Dec 13, 2013 at 14:34
  • I think you mean if(NULL == f), it isn't going to compile with only a single =.
    – Kninnug
    Dec 13, 2013 at 14:37
  • @Kninnug: That's why I put the NULL first. Thanks for taking over the compiler's part ... ;-)
    – alk
    Dec 13, 2013 at 14:39
  • Yep, +1 for using Yoda conditions. That would have been an annoying bug otherwise.
    – Kninnug
    Dec 13, 2013 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.