C言語を使用して、タスク情報を記録できるシステムを作成しています。addtaskで受け取った情報をtxtファイルに追加しviewtaskで開くコードを書こうと試みています。しかしコードを実行したところ、menuから2を押し、txtファイルが開けず、実行画面が終了しました。
以下にソースコードをupしますので、原因と解決方法をご教授いただけますと幸いです。
c
1#include <stdio.h> 2#include <stdlib.h> 3 4 5void addtask(); 6void viewtask(); 7 8int main() { 9 char selection ; 10 11 do 12 { 13 selection = menu(); 14 switch(selection) 15 { 16 case '1': addtask(); 17 break; 18 case '2': viewtask(); 19 break; 20 default: 21 printf("\nYou entered wrong choice..."); 22 printf("\nPress any key to try again"); 23 break; 24 } 25 } 26 while(selection != '9'); 27 return 0; 28} 29 30char menu() { 31 printf("\n\n\nWelcome to Task Management System!"); 32 printf("\nThis is Main Menu"); 33 char option; 34 printf("\n1) Add New Task"); 35 printf("\n2) Check your Task"); 36 printf("\nEnter your choice: "); 37 scanf("%c[^\n]", &option); 38 return option; 39} 40 41void addtask() 42{ 43 int id, value; 44 printf("\nthis is add your Task"); 45 FILE * f = fopen("data.txt", "r+"); 46 if(f == NULL) 47 f = fopen("data.txt", "w"); 48 else 49 { 50 fseek(f, 0, SEEK_END); 51 char tsn[8]; 52 printf("Enter your Task name\n"); 53 scanf("%s", tsn); 54 printf("\nENTER id:"); 55 scanf("%d", &id); 56 printf("\nEnter value: "); 57 scanf("%d", &value); 58 fprintf(f,"%s %d %d\n", tsn, id, value); 59 } 60 fclose(f); 61} 62 63void viewtask(){ 64 int i ,v; 65 char tsn; 66 printf("\nthis is display record"); 67 FILE * f = fopen("data.txt", "r"); 68 while(fscanf(f,"%s",&tsn) != EOF){ 69 fscanf(f,"%d", &i); 70 fscanf(f,"%d",&v); 71 printf("\n task name: %s \t id: %d \t Value: %d",tsn, i, v); 72 } 73 fclose(f); 74}
> txtファイルが開けず、
開けなかったのならまあクラッシュしますね。
data.txt はカレントディレクトリに存在するのですか? 存在するなら、具体的にどんな内容になってますか?
viewtask() の中で fopen() のエラーチェックや fscanf() のエラーチェックをしたほうが原因の究明に役立つと思います。
回答1件
あなたの回答
tips
プレビュー