2013-02-22 56 views
-2

我在这里有点新,所以我提前道歉,如果我没有足够的解释,所以在这里它:如何检查文本的文本文件,然后存储变量?

为了给你一个图片,我有一个fopen命令打开和/或创建一个文本文件参数读/写/重写,如果我是正确的

fp = fopen("stats.txt", "w+"); 

我已经将文件写入到具有:

void display_stats() 
{ 
//some math needed for calculations 
smod = (STR - 10)/2; 
dmod = (DEX - 10)/2; 
cmod = (CON - 10)/2; 
imod = (INT - 10)/2; 
wmod = (WIS - 10)/2; 
hmod = (CHR - 10)/2; 
amod = (APP - 10)/2; 

//print to console 
printf("STR: %i(%i)\n", STR, smod); 
printf("DEX: %i(%i)\n", DEX, dmod); 
printf("CON: %i(%i)\n", CON, cmod); 
printf("INT: %i(%i)\n", INT, imod); 
printf("WIS: %i(%i)\n", WIS, wmod); 
printf("CHR: %i(%i)\n", CHR, hmod); 
printf("APP: %i(%i)\n", APP, amod); 
printf("-----Saving Throws------\n"); 
printf("Fortitude: %i\n", fort); 
printf("Reflex: %i\n", rflx); 
printf("Will: %i\n", will); 

// write to file 
fprintf(fp, "Level %i %s %s:\n",level,race_r,spec_c); 
fprintf(fp, "STR: %i(%i)\n", STR, smod); 
fprintf(fp, "DEX: %i(%i)\n", DEX, dmod); 
fprintf(fp, "CON: %i(%i)\n", CON, cmod); 
fprintf(fp, "INT: %i(%i)\n", INT, imod); 
fprintf(fp, "WIS: %i(%i)\n", WIS, wmod); 
fprintf(fp, "CHR: %i(%i)\n", CHR, hmod); 
fprintf(fp, "APP: %i(%i)\n", APP, amod); 
fprintf(fp, "Fort save: %i\n", fort); 
fprintf(fp, "Reflex save: %i\n", rflx); 
fprintf(fp, "Will save: %i\n", will); 

} 

其输出这在文件“stats.txt”(取决于用户什么输入)

Level 2 Gnome Sorcerer: 
STR: 8(-1) //STR=8 smod=-1 
DEX: 14(2) //DEX=14 dmod=2 
CON: 14(2) //etc... 
INT: 13(1) 
WIS: 13(1) 
CHR: 12(1) 
APP: 11(0) 
Fort save: 0 
Reflex save: 0 
Will save: 3 

现在,对于节目第二轮,我希望它来检查文件的文本,如果属实,那么输出的文本与存储所有变量供以后使用以来,我目前有:

if (fgets(buf, 1000, fp) == NULL) //char buf[1000]/FILE fp if "stats.txt" has no text 
       { 
        printf("Please enter in your base stats (no modifiers):\n"); 
        enter_stats(); 
        printf("Please indicate your characters level:\n"); 
        printf("I am a level "); 
        level = GetInt(); 
        Race_check(); 
        spec_check(); 
        printf("------Base saving throws (no modifiers)------\n"); 
        saving_throws(); 
       } 
       else //if "stats.txt" has text 
       { 
        printf("%s",buf); 
       } 
       break; //ending of a case statement 

请和谢谢你的帮助,这是令人沮丧的。

+1

你有问题吗? – melpomene 2013-02-22 09:48:07

+1

怎么回事?你已经打开文本文件。你现在可以逐行读取它?然后将其存储到您的程序中的一个简单的var。 – 2013-02-22 09:51:56

回答

0

由于你没有写任何问题,我猜它是像'它只读一行'的东西。

这是因为fgets函数只能读取到n-1个字符或达到换行符

更多信息here

0
FILE* fp1; 

    FILE* fp2 

    fp1 = fopen("text_to_read","r"); 

    fp2 = fopen("text_to_write","w+"); 

    char* s; 

    while(fscanf(fp,"%s",s) != EOF) 

{

fprintf(fp2,"%s",s); 

}

printf("Its done!!") 
相关问题