Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. Malliratkaisu
  2.  
  3. #include <stdio.h>
  4.  
  5. /* tehdään rakenteesta globaali */
  6. struct henkilo{
  7. char etunimi[20+1];
  8. char sukunimi[20+1];
  9. char puhelin[20+1];
  10. };
  11.  
  12. int main(void)
  13. {
  14. struct henkilo hloTaulukko[50];
  15. const char *tiedNimi = "luettelo.txt";
  16. int i, tietoja;
  17. FILE *fp;
  18.  
  19. /* haetaan tiedostosta vanhat tiedot */
  20. if((fp = fopen(tiedNimi,"r")) == NULL){
  21. printf("tiedoston %s avaaminen epäonnistui\n", tiedNimi);
  22. exit(1);
  23. }
  24. fscanf(fp,"%d", &tietoja);
  25. for(i=0;i<tietoja;i++){
  26. fscanf(fp,"%s %s %s",
  27. hloTaulukko[i].etunimi, hloTaulukko[i].sukunimi, hloTaulukko[i].puhelin);
  28. }
  29. fclose(fp);
  30.  
  31. /* uuden tiedon kysyminen */
  32. printf("Anna etunimi:");
  33. scanf("%s", hloTaulukko[tietoja].etunimi);
  34. printf("Anna sukunimi:");
  35. scanf("%s", hloTaulukko[tietoja].sukunimi);
  36. printf("Anna puhelinnumero:");
  37. scanf("%s", hloTaulukko[tietoja].puhelin);
  38.  
  39. /* tietojen päivittäminen tiedostoon */
  40. if((fp = fopen(tiedNimi,"w")) == NULL){
  41. printf("tiedoston %s avaaminen epäonnistui\n", tiedNimi);
  42. exit(1);
  43. }
  44. fprintf(fp,"%d\n",++tietoja);
  45. for(i=0;i<tietoja;i++){
  46. fprintf(fp,"%s %s %s\n",
  47. hloTaulukko[i].etunimi, hloTaulukko[i].sukunimi, hloTaulukko[i].puhelin);
  48. }
  49.  
  50. printf("Tietojen tallennus onnistui.\n");
  51.  
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement