[英]reading from text file and using data in c
在给定的文本文件中编写数组和结构并在计算中将其检索给我们有人可以帮助我提供示例代码这是我的代码
#include <stdio.h>
#include <stdlib.h>
int main()
{ FILE *file1;
FILE *file2;//declaring two file pointers file1 to read,and file2 to read
file1=fopen("data.txt","w"); //creating a new text file in writing mode
int array1[12],i;//declared array1 which we will input the data in
for(i=0;i<=12;i++){
scanf("%d",&array1[i]);//i am trying to use a for loop to input elements into arrar
fprintf(file1,array1);//am trying to write the gotten values into file1
}
fclose(file1);
file2=fopen("data.txt","r");//in read mode a file2 poninter
int array2[12]; //another array of same number of elements to store the data read from file
while(!feof(file2)){ //to get all the values inthe text file
for(i=1;1<=12;i++){
fscanf(file2,"%d",&array2[i]);//from here i am just confused
printf("%d",array2[12]);
}
}
fclose(file2);
}
array1
和array2
被声明为包含 12 个元素,每个元素编号从 0 到 11(总共 12 个) for
循环需要适应这一事实。`fprintf
需要三个 arguments int fprintf(FILE *fptr, const char *str, ...);
请注意@Some程序员老兄和@Jabberwocky发表的评论
实施更正,您的代码应如下所示......在我所做的更改处放置了评论......希望它们对您有所帮助......
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file1;
FILE *file2;
file1=fopen("data.txt","w");
int array1[12],i;
if(file1 != NULL){
for(i=0;i<12;i++){//i needs to be less than 12
scanf("%d",&array1[i]);
fprintf(file1,"%d\n",array1[i]);//fprintf needs three arguments
}
}
fclose(file1);
file2=fopen("data.txt","r");
int array2[12];
if(file2 != NULL){ //to get all the values inthe text file
for(i=0;i<12;i++){//i needs to be less than 12
fscanf(file2,"%d",&array2[i]);
printf("%d\n",array2[i]);
}
}
fclose(file2);
}
我会将错误处理(如果文件无法打开)留给您作为练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.