[英]Read and write multiple line data file in C
I'm having trouble reading and writing more than one line of data from a file. 我在从文件读取和写入多行数据时遇到麻烦。 The problem is to read multiple lines of binary from a file and convert it to decimal and write the multiple lines of decimal to a new file.
问题是从文件中读取多行二进制并将其转换为十进制,然后将多行十进制写入新文件。 I had no problem getting the program to convert one line of binary to decimal the trouble comes when I have multiple lines.
我没有问题让程序将二进制的一行转换为十进制,当我有多行时,麻烦就来了。 Here is my code so far:
到目前为止,这是我的代码:
#include <stdio.h>
#include <string.h>
#define NULL 0
int main() {
FILE *ptdata, *ptresult;
char bin[32];
int i, r = 0, len;
ptdata = fopen("data.txt", "r");
ptresult = fopen("result.txt", "w");
if (ptdata == NULL) printf("Error cannot open file");
else {
while (fgets(bin, 32, ptdata) != NULL);
len = strlen(bin);
for (i = 0; i < len; i++) {
r = r * 2 + (bin[i] == '1' ? 1 : 0);
}
printf("%d\n", r);
fprintf(ptresult, "%d\n", r);
fclose(ptdata);
fclose(ptresult);
}
return 0;
}
Here is the error: 这是错误:
while(fgets(bin,32,ptdata)!=NULL);
//^^^You have semicolon
//here which ends the while loop
You should do the following: 您应该执行以下操作:
while(fgets(bin,32,ptdata)!=NULL){
len = strlen(bin);
r = 0 ;
for(i = 0; i < len; i++)
{
r = r * 2 + (bin[i] == '1' ? 1 : 0);
}
printf("%d\n",r);
fprintf(ptresult,"%d\n",r);
}
Your while loop has been prematurely terminated 您的while循环已提前终止
while(fgets(bin,32,ptdata)!=NULL);
^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.