#2
by かずま » 8年前
次のプログラムは参考になりますか?
何が分かっって、何が分からないか返事を下さい。
コード:
#include <stdio.h> // printf, fopen, fclose, fscanf, fprintf
#include <stdlib.h> // malloc, srand, rand
#include <time.h> // time
#define SAVEFILE "save.txt"
struct LIST {
struct LIST *next;
int value;
};
struct LIST *plist = NULL;
int main(void)
{
FILE *fp = fopen(SAVEFILE, "r");
srand((unsigned)time(NULL));
while (1) {
int random = 0;
if (fp && fscanf(fp, "%d", &random) != 1) {
fclose(fp);
fp = NULL;
}
if (!fp) {
int q = getchar();
if (q == 'q') break;
if (q != '\n') continue;
random = rand() % 1000;
if (random < 100) random += 100;
}
struct LIST *p = (struct LIST *) malloc(sizeof(struct LIST));
p->value = random;
p->next = NULL;
if (plist == NULL)
plist = p;
else {
struct LIST *prev = plist;
while (prev->next != NULL) prev = prev->next;
prev->next = p;
}
if (!fp) printf(" %d\n", p->value);
}
fp = fopen(SAVEFILE, "w");
struct LIST *p = plist;
while (p != NULL) {
if (fp) fprintf(fp, "%d\n", p->value);
printf("\n%d", p->value);
p = p->next;
}
if (fp) fclose(fp);
getchar();
getchar();
return 0;
}
このプログラムをどこから起動してもよいようにするためには
SAVEFILE をフルパスにするとか、ユーザごとに異なったファイルにする
などの修正が必要でしょう。
質問するときは、フォーラムルールをよく読んで、
プログラムを添付するときは、codeタグを使うようにしてください。
次のプログラムは参考になりますか?
何が分かっって、何が分からないか返事を下さい。
[code=c]
#include <stdio.h> // printf, fopen, fclose, fscanf, fprintf
#include <stdlib.h> // malloc, srand, rand
#include <time.h> // time
#define SAVEFILE "save.txt"
struct LIST {
struct LIST *next;
int value;
};
struct LIST *plist = NULL;
int main(void)
{
FILE *fp = fopen(SAVEFILE, "r");
srand((unsigned)time(NULL));
while (1) {
int random = 0;
if (fp && fscanf(fp, "%d", &random) != 1) {
fclose(fp);
fp = NULL;
}
if (!fp) {
int q = getchar();
if (q == 'q') break;
if (q != '\n') continue;
random = rand() % 1000;
if (random < 100) random += 100;
}
struct LIST *p = (struct LIST *) malloc(sizeof(struct LIST));
p->value = random;
p->next = NULL;
if (plist == NULL)
plist = p;
else {
struct LIST *prev = plist;
while (prev->next != NULL) prev = prev->next;
prev->next = p;
}
if (!fp) printf(" %d\n", p->value);
}
fp = fopen(SAVEFILE, "w");
struct LIST *p = plist;
while (p != NULL) {
if (fp) fprintf(fp, "%d\n", p->value);
printf("\n%d", p->value);
p = p->next;
}
if (fp) fclose(fp);
getchar();
getchar();
return 0;
}
[/code]
このプログラムをどこから起動してもよいようにするためには
SAVEFILE をフルパスにするとか、ユーザごとに異なったファイルにする
などの修正が必要でしょう。
質問するときは、フォーラムルールをよく読んで、
プログラムを添付するときは、codeタグを使うようにしてください。