我正在尝试从K& R C 2.9获取getbits并传递包含ints的文本文件,检查以确保getbits()可以处理它们,并将输出格式化为另一个txt文件。我很难过,我的导师告诉我不要使用fscanf,使用stdin和scanf。
这是我的代码
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
我知道这是基本的,但我真的很赞赏任何帮助:)
答案 0 :(得分:1)
您还可以在不使用fscanf
的情况下从文件中读取整数。以下是一些从文件中读取内容的代码,而不使用fscanf
。我还更正了您将int
数据与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;
}
对于Windows,请使用以下解决方案:
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;
}