c - 在c中更新随机访问文件

标签 c

我想在 C 中执行以下操作。

我有一个包含一些记录的随机访问数据文件。

记录格式如下:

Acct#  First Name     Last Name    Balance
0     ""             ""             0.0
0     ""             ""             0.0
0     ""             ""             0.0
05    Joe             Costanza      0.50
 0     ""             ""             0.0
 0     ""             ""             0.0
 0     ""             ""             0.0
19    Jason           Bourne        58.00
0     ""              ""            0.0
0     ""             ""             0.0
42    Andy            Der          -15.12
0     ""             ""             0.0
0     ""             ""             0.0

我想从所有具有非零帐号的记录的余额中减去一个金额,并将新更新的余额写入这些记录的文件。

这是我迄今为止为完成上述目标所做的尝试。

#include <stdio.h>

struct clientData 
{ 
int acctNum;          
char lastName[15];  
char firstName[10]; 
double balance;       
};

void textFile(FILE *readPtr);

int main(void)
{ 
     FILE *cfPtr;

     struct clientData client = {0, "", "", 0.0};

     double serviceCharge = 5.0;

     cfPtr = fopen("credit.dat", "rb+");

     fread(&client, sizeof(struct clientData), 1, cfPtr);

     client.balance -= serviceCharge;

     fseek(cfPtr,(client.acctNum - 1) * sizeof(struct clientData)
     , SEEK_CUR);

     fwrite(&client, sizeof(struct clientData), 1, cfPtr);

     fclose(cfPtr);

     return 0;
}

无论我尝试什么,我都无法将单个更新记录写回文件。我什至尝试过没有任何 while 循环或 if 语句的单个记录,但它仍然不起作用。谁能告诉我我错过了什么。

循环:

fread( &client, sizeof( struct clientData ), 1, cfPtr);

while (!feof(cfPtr))
{ 
if ( client.acctNum != 0 )
{
    client.balance -= serviceCharge;
    fseek(cfPtr, (-1 * sizeof(struct clientData)), SEEK_CUR); 

    fwrite( &client, sizeof( struct clientData ), 1, cfPtr);
}

fread( &client, sizeof( struct clientData ), 1, cfPtr);
}

最佳答案

     while ( !feof( readPtr ) )
     { 
         if ( client.acctNum != 0 )
         {

此时在代码中,您还没有阅读任何内容。没有什么。 :)

您已经打开了文件,您已经检查是否已经到达文件末尾,但是还没有代码可以从文件中读取任何内容,所以您的 if 条件只是在开始时检查初始化的结构。

如果在循环的顶部读取输入,则循环输入通常效果最好。 (也有异常(exception),但这看起来不像其中之一。)

尝试将此作为循环的起点:

while(fread(&client, sizeof(struct clientData), 1, filePtr)) {
    if (client.acctNum) {
        client.balance -= charge;
        fseek(filePtr, - sizeof(struct clientData), SEEK_CUR);
        if (1 != fwrite(&client, sizeof(struct clientData), 1, filePtr))
            perror("Error writing to file");
    }
}

错误处理或许可以改进;也许应该中止整个编辑。 (文件上的强制记录锁定可能会导致某些 写入失败而某些写入成功,但这种情况的可能性很小。)

更新

您的 fseek() 调用基于帐号乘以 struct clientData 的大小来确定新文件位置。仅当您的记录已排序,没有数字被跳过,并且它从 0 开始并向上运行时,这才有效。 (您的示例输入文件未排序;您甚至在“有效”记录中间有一个帐号为 0 的记录。)所以切换到 fseek(..., SEEK_CUR) 代替。

关于c - 在c中更新随机访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5574063/

相关文章:

c - 通过网络 Ubuntu 和 C 发送声音

c - 局部静态变量是嵌入式编译器提供的吗?

c - 如何在流套接字字节流中查找特定字符串

c++ - 如何确保在不满足条件时不运行特定代码

c - Eclipse C Build 选定的文件不生成可执行文件

c - 函数工作正常,但返回垃圾

c++ - 固定大小数组与 alloca(或 VLA)

c - C编程基础题

Centos7上安装HAWQ时编译错误:

c++ - 如何在 C/C++ 中使用 WinHTTP 下载文件?