问题描述
在这里,我想将字符串str写入文件log.dat
。当str
的单词之间有空格时,我遇到了问题。
我要编写的代码:
fp=fopen("log.dat","ab");
fwrite(str,1,sizeof(str),fp);
阅读:
char c;
fp = fopen("log.dat","rb");
c = fgetc(fp);
while (c != EOF)
{
printf("%c",c);
c = fgetc(fp);
}
解决方法
对于您的代码,有些未知的事情可能会失败或导致未定义的行为,例如,您是在打开文件以进行读取之前关闭文件吗?
这就是发布minimal-reproducible-example的重要性。
情况就是这样,一般来说,您应该如何做:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *str = "this is my string,";
FILE *fp;
fp = fopen("log.dat","ab");
if (fp == NULL){ //check for fopen failure
perror("fopen");
return EXIT_FAILURE;
}
int num_chars = 0;
if((num_chars = fwrite(str,1,strlen(str),fp)) == 0){ //no data was written
puts("No data was written to the file."); //you can adapt check to your needs
return EXIT_FAILURE;
}
fclose(fp); //close fp
fp = fopen("log.dat","rb");
if (fp == NULL){ //check for fopen failure
perror("fopen");
return EXIT_FAILURE;
}
int c;
int i = 0;
char string[num_chars];
int count_chars = 0;
while ((c = fgetc(fp)) != EOF) {//read until end of file
count_chars++; //count characters
//printf("%c",c);
string[i++] = c; //assign the string,it's much easier to remove the last char
}
if(i > 0)
string[i - 1] = '\0'; //overwrite last char with a null byte
if(count_chars == 0){ // if count is 0 file has nothing
puts("File is empty");
}
else{
printf("\n%d characters were read\n",count_chars);
puts(string);
}
}
其中一些变量重复的值strlen(string)
,count_chars
和num_chars
应该具有相同的值,但是有意区分它们是为了模拟真实的程序场景,在这种情况下,读写错误可能发生。
主题外
您应该替换此尴尬的代码:
// Use only `/increment` instead of `increment/:id`.
app.use("/increment",itemRoutes);
与此:
c = fgetc(fp);
while (c != EOF)
{
printf("%c",c);
c = fgetc(fp);
}
始终尝试避免无用的重复。
减少话题:
while ((c = fgets(fp)) != EOF)
{
printf("%c",c);
}
返回一个fgetc
而不是一个字符,因此您需要声明int
而不是int c;