我想更新并比较该文件。 如何编写代码以获得以下结果?
首先运行程序,获取数据akon : 5
,我需要保存到txt文件中:
akon : 5
第二次运行,获取数据john : 10
akon : 5
john : 10
第3次运行,获取数据akon : 2
akon : 2
john :10
第4次运行,获取数据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
答案 0 :(得分:0)
我建议您尝试使用Python等高级语言首先制作您想要的内容。以下python代码可以满足您的需求。
您应该能够遵循此代码并找到等效的C方法来完成相同的任务。最复杂的部分可能是决定如何存储播放器/分数对(在Python中是微不足道的,但不幸的是C没有字典)。
# 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')
一些提示:
fscanf(file, "%s : %d", name, score)
替换大部分split
和strip
代码。struct { char* e_name; int e_score; } entry;