File io 文件i/o以更新C中的文件

File io 文件i/o以更新C中的文件,file-io,File Io,我想更新和比较文件。 如何编写代码以获得以下结果 首先运行程序,获取数据akon:5,我需要保存到txt文件中: akon : 5 第二次运行,获取数据约翰:10 akon : 5 john : 10 第三次运行,获取数据akon:2 akon : 2 john :10 第四次运行,获取数据akon:3 akon : 3 john : 10 下面是我键入的代码,但我被困在这里 FILE *out_file; char name[100]; int score; printf("ple

我想更新和比较文件。 如何编写代码以获得以下结果

首先运行程序,获取数据akon:5,我需要保存到txt文件中:

akon : 5
第二次运行,获取数据约翰:10

akon : 5
john : 10
第三次运行,获取数据
akon:2

akon : 2
john :10
第四次运行,获取数据
akon:3

akon : 3
john : 10
下面是我键入的代码,但我被困在这里

FILE *out_file; 
char name[100];
int score;

printf("please enter name:");
gets(name);

printf("please enter the score:");
scanf("%d",&score);
out_file= fopen("C:\\Users/leon/Desktop/New Text Document.txt", "w"); // write only 

      // test for files not existing. 
      if (out_file == NULL) 
        {   
          printf("Error! Could not open file\n"); 
          exit(-1); // must include stdlib.h 
        } 

      // write to file 
      fprintf(out_file, "%s : %d",name,score); // write to file 

我建议首先尝试用更高级的语言(如Python)来原型化您想要的东西。下面的python代码可以满足您的需求

您应该能够遵循这段代码并找到等效的C方法来完成相同的任务。最复杂的部分可能是决定如何存储player/score对(在Python中很简单,但不幸的是C没有字典)

以下是一些提示:

  • fscanf(文件“%s:%d”、名称、分数)
    替换大部分
    split
    strip
    代码
  • struct{char*e_name;int e_score;}条目
  • 看看这个关于结构数组的答案

我不确定您的问题是什么,或者您发布的代码有什么问题。你能把你的问题说得更清楚一点吗?请不要使用
get()
;这很危险。它甚至不再是标准C的一部分(它已从C11标准中删除)。改用
fgets()
;这不会导致缓冲区溢出。目标是读取名称和分数,并使用新分数更新具有相同名称的现有条目,还是在名称不在文件中时写入新名称和分数?
# Equivalent to C/C++ include
import sys

# Create dictionary to store scores
data = {}

# Check for existence of scores files
try:
    with open("data.txt", 'r'): pass
except IOError: pass

with open("data.txt", 'r') as fp:
    for line in fp:
        # Split line by ':'
        parts = line.split(':')

        # Check that there are two values (name, score)
        if len(parts) != 2: continue

        # Remove white-space (and store in temporary variables)
        name = parts[0].strip()
        score = parts[1].strip()

        # Store the name and score in dictionary
        data[name] = score

# Get input from user
update_name = raw_input('Enter player name: ')
update_score = raw_input('Enter player score: ')

# Update score of individual
data[update_name] = update_score

# Write data to file (and to screen)
with open("data.txt", 'w') as fp:
    for name,score in data.items():
        output = "{0} : {1}".format(name,score)

        print output
        fp.write(output + '\n')