簡體   English   中英

從文本文件中讀取並使用 c 中的數據

[英]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);

}
  • array1array2被聲明為包含 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM