简体   繁体   English

从文本文件中读取并使用 c 中的数据

[英]reading from text file and using data in c

to write arrray and structures in a given text file and retrieving it to us in calculation can somebody help me with a sample code this is my code在给定的文本文件中编写数组和结构并在计算中将其检索给我们有人可以帮助我提供示例代码这是我的代码

#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 and array2 are declared to hold 12 elements each ieelements numbered from 0 to 11(total 12).The for loops need to accommodate this fact.` array1array2被声明为包含 12 个元素,每个元素编号从 0 到 11(总共 12 个) for循环需要适应这一事实。`
  • fprintf requires three arguments int fprintf(FILE *fptr, const char *str, ...); fprintf需要三个 arguments int fprintf(FILE *fptr, const char *str, ...);

Please take notice of the comments posted by @Some programmer dude and @Jabberwocky请注意@Some程序员老兄和@Jabberwocky发表的评论

Implementing the corrections your code should look like this......have placed comments where I made changes.....hope they are helpful....实施更正,您的代码应如下所示......在我所做的更改处放置了评论......希望它们对您有所帮助......

#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);
}

I will leave error handling (if the file fails to open) as an exercise for you.我会将错误处理(如果文件无法打开)留给您作为练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM