gpt4 book ai didi

c - 搜索数据并将数据从一个文件写入另一个文件

转载 作者:行者123 更新时间:2023-12-04 10:05:34 24 4
gpt4 key购买 nike

我需要编写一个 C 程序来从一个文件中获取数据并将其写入另一个文件,而不使用用户定义的函数。我的要求是:

  • Search customer details by Name.
  • Store the transaction data (paid amount) in another text file.


我做了代码以按名称搜索。但它不起作用,
#include <stdio.h>
#include <stdlib.h>

int main () {
char name[10], nic[10], mobile[10];
char fname[10], fnic[10], fmobile[10];
char choice;
int amount;
FILE *cfptr;


printf("Enter search type - \n 1. NAME \n 2. NIC \n 3.MOBILE \n ----> ");
scanf("%c", &choice);

printf("Enter search text : ");
scanf("%s", &name);

cfptr = fopen ("customer.dat", "r");

while (!feof(cfptr)){

fscanf(cfptr, "%s %s %s", fname, fnic, fmobile);

printf("Read Name |%s|\n", fname );
printf("Read NIC |%s|\n", fnic );
printf("Read Mobile |%s|\n", fmobile );
}
fclose(cfptr);
scanf("%d", &amount);

return(0);
}

客户.dat文件
Shan    100012  200202
Marsh 121213 667675
Kim 126573 663412

此代码不完整,因为我无法过滤分配的单个名称
if(name == fname)

正如我得到的

assignment to expression with array type error



任何人都可以完成我搜索并保存到另一个文件的代码,以便我可以进行金额计算部分吗?

最佳答案

int Search_in_File(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];

//gcc users
//if((fp = fopen(fname, "r")) == NULL) {
// return(-1);
//}

//Visual Studio users
if((fopen_s(&fp, fname, "r")) != NULL) {
return(-1);
}

while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}

if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}

//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}

关于c - 搜索数据并将数据从一个文件写入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61605735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com