2012-03-14 79 views
-2

我正在写一个程序的自动取款机。我.txt文件是一个账户余额(在这种情况下,1500.00)。如何在.txt文件读取,编辑帐户余额,然后将其保存到文件?如何在C中读取和编辑.txt文件?

例如,如果我要求用户输入一笔金额为300.00的存款,我希望能够将300.00添加到文件中现有的1500.00,然后覆盖1500.00,总金额为1800.00。

这是我到目前为止。

float deposit; 
    float var; 

printf("Current account balance:"); 
if ((file_account = fopen ("account.txt", "r")) == NULL) 
{ 
    printf ("Error finding account balance.\n"); 
    return; 
} 

while ((fscanf (file_account, "%c", &var)) != EOF) 
{ 
    printf ("%c", var); 
} 
printf ("\n"); 
fclose (file_account); 

for (deposit=0; deposit>0; deposit++) 
{ 
    if (deposit > 0) 
    { 
     printf ("Enter amount to deposit:"); 
     scanf ("%f", &deposit); 
     //file_account + deposit; 
     fprintf (file_account, "Your new account balance is: %f", deposit); 
    } 
    else 
    { 
     printf ("Amount must be 0 or more."); 
    } 
    fclose (file_account); 

}

+4

有什么你到目前为止尝试过?你研究了什么?我没有看到这方面的努力。 – 2012-03-14 19:13:05

+1

如果这是家庭作业,请将其标记为[功课。如果不是,... – 2012-03-14 19:18:38

+0

对不起,我是新手! – user1269888 2012-03-14 19:21:15

回答

1

你需要几个步骤在这里:

int triedCreating = 0; 

OPEN: 
FILE *filePtr = fopen("test.txt", "r+"); 

if (!filePtr) 
{ 
    // try to create the file 
    if (!triedCreating) 
    { 
     triedCreating = 1; 
     fclose(fopen("test.txt", "w")); 
     goto OPEN; 
    } 
    fprintf(stderr, "Error opening file %i. Message: %s", errno, strerror(errno)); 
    exit(EXIT_FAILURE); 
} 

// scan for the float 
float value = 0.0f; 
fscanf(filePtr, "%f", &value); 

printf("current value: %f\nvalue to add: ", value); 

// add the new value 
float add = 0.0f; 
scanf("%f", &add); 

value += add; 

// write the new value 
fseek(filePtr, 0, SEEK_SET); 

fprintf(filePtr, "%f", value); 

fclose(filePtr); 

您可能希望有不同的格式为您printf()的,这样当读取到一个普通的文本编辑器,它看起来更好。

+0

我定义我的文件指针在main(file_account)。这是我打来的功能。我会多玩几次。感谢您的帮助!对此,我真的非常感激。 – user1269888 2012-03-14 19:37:20

+0

@ user1269888没问题!只要确定接受答案:) – 2012-03-14 19:38:46

0

你应该用一个文件指针,打开&读取该文件,修改内容根据您的意愿和写回文件。

例如:

File *fp; // creates a pointer to a file 
fp = fopen(filename,"r+"); //opens file with read-write permissions 
if(fp!=NULL) { 
    fscanf(fp,"%d",&var);  //read contents of file 
} 

fprintf(fp,"%d",var);   //write contents to file 
fclose(fp);     //close the file after you are done 
+0

'rw'不是一个有效的fopen说明符。你可能想要'r +'或'w +'。 – 2012-03-14 19:28:25

+0

对不起,没有意识到 – Chaos 2012-03-14 19:29:40

0

你可以阅读和编辑文件,基本的文件的帮助I/O(输入/输出)在C I例如像一个简单的方式功能,写入文件如果它存在,并且如果不创建名称的文件,然后写入它。

基础教程可以在 http://www.tutorialspoint.com/cprogramming/c_file_io.htm

现在发现,如果你谈论的是有很多的在它的内容复杂的.txt文件,然后你需要找到一个特定的词,并改变它,我觉得在Linux中你可以调用脚本来读取文件,使用SED进行编辑(用于过滤和转换文本的流编辑器),这在Linux中有点困难。您可以在下面的链接找到它的教程 http://www.panix.com/~elflord/unix/sed.html