Question

I'm trying to take getbits from K&R C 2.9 and pass a text file containing ints through, check to make sure getbits() can handle them, and format the ouput to another txt file. I'm stumped and my instructor told me NOT to use fscanf, use stdin and maybe scanf.

Here's my code

include <stdio.h>


unsigned int getbits(unsigned int x, int p, int n) 
{
  return (x >> (p + 1 - n)) &  ~(~0 << n);
}


int main()
{
  File * ipf = fopen("input.txt", "r");
  int x = 0 , p = 0, n = 0, b = 0;

  while(fscanf(ipf, "%d, %d, %u", &p, &n, &x) != EOF)
  {

    if(x < 4294967296 && p < 32 && n < p + 2)
    { 
      b = getbits(x,p,n);
      printf("gebits( x = %u, p = %d, n =  %d) = %u\n", x, p, n, b);
    } 
    else { printf("ERROR"); }
  }

  return 0;
}

input.txt

2,1,127
2,4,127
31,3,1431655765
32,3,1431655765

output.txt

getbits(x=127, p=2, n=1) = 1
ERROR
getbits(x=1431655765, p=31, n=3) = 2
ERROR

I know this is all basic but I really apreciate any help :)

Was it helpful?

Solution

You can also read an integer from the file without using fscanf. Here is some code which reads content from the file, without using fscanf. I also corrected some data type declaration for your value in which you compared int data to long long.

int main()
{
    FILE * ipf = fopen("input.txt", "r");
    long long x = 0 , p = 0, n = 0, b = 0;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    char *token;

      while ((read = getline(&line, &len, ipf)) != -1)
      {   
            token=strtok(line,",");
            p=atoi(token);

            token=strtok(NULL,",");
            n=atoi(token);

            token=strtok(NULL,"");
            x=atoi(token);

            if(x < 4294967296 && p < 32 && n < p + 2)
            { 
              b = getbits(x,p,n);
              printf("gebits( x = %lld, p = %lld, n =  %lld) = %lld\n", x, p, n, b);
            } 
            else { printf("ERROR\n"); }
      }

  return 0;
}

For Windows, use the following solution:

int main()
{
    FILE * ipf = fopen("input.txt", "r");
    long long x = 0 , p = 0, n = 0, b = 0;
    char line [256];
    size_t len = 0;
    ssize_t read;
    char *token;

  while ((fgets(line,256, ipf)) != 0)
  {   
        token=strtok(line,",");
        p=atoi(token);

        token=strtok(NULL,",");
        n=atoi(token);

        token=strtok(NULL,"");
        x=atoi(token);

        if(x < 4294967296 && p < 32 && n < p + 2)
        { 
          b = getbits(x,p,n);
          printf("gebits( x = %lld, p = %lld, n =  %lld) = %lld\n", x, p, n, b);
        } 
        else { printf("ERROR\n"); }
  }

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top