我需要打开一个文件进行读写.如果找不到该文件,则应该创建该文件.它也应该被视为Windows的二进制文件.你能告诉我我需要使用的文件模式序列吗?
我试过'r + ab'但是如果找不到它们就不会创建文件.
谢谢
我想打开一个文件,读取其内容,然后在文件中附加一行.我以为我应该使用"a +"标志来完成任务.
我有一个打开文件并返回指向该文件的指针的函数.
FILE* open_weekly_disk_file(char* filename){
FILE* weekly_log;
weekly_log = fopen(filename, "a+");
//weekly_log = fopen(filename, "r");
if(! weekly_log){
printf("The attempt to open the weekly log failed!\n");
return NULL;
} else{
return weekly_log;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个函数调用上面的函数并使用scanf从文件中读取内容:
void sample_function(char* filename){
FILE* log;
char token[100], current_read[100];
int limit;
log = opened_weekly_disk_file(filename);
// The problem happens here
for(limit=0; limit < TOKEN_NUMBER; limit++){
if(fscanf(log, "%s%s", &token, ¤t_read) == 2){
printf("%s %s\n", token, current_read);
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
我使用时此代码有效:
weekly_log = fopen(filename, "r");
Run Code Online (Sandbox Code Playgroud)
但是当我将"r"标志更改为"a +"时不起作用.我在for循环之前得到了一个Segmentation错误.