简体   繁体   English

从 C 中的文件读取时出现奇怪的字符

[英]Strange characters when reading from file in C

So I am just trying to learn C and have decided to program a simple calendar where you can add events etc. It is working almost perfectly however, when it tries to read from the file containing the information, the first line contains some strange characters: �<�}�U1.所以我只是想学习 C 并决定编写一个简单的日历,您可以在其中添加事件等。它工作得几乎完美但是,当它尝试从包含信息的文件中读取时,第一行包含一些奇怪的字符: �<�}�U1.

Code is as follows:代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void createCalendar(char filename[]) {
    FILE *cptr;
    cptr = fopen(filename, "w");
    char dates[177/sizeof(char)] = "";
    for(int i = 1; i < 32; i++) {
        char strtowrite[7/sizeof(char)] = "";
        sprintf(strtowrite, "%d - \n", i);
        strcat(dates, strtowrite);
    }
    fprintf(cptr, "%s", dates);
    fclose(cptr);
}

void addToDay(char filename[], int day, char event[]) {
    FILE *cptr;
    cptr = fopen(filename, "r");
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    char dates[177/sizeof(char) + strlen(event)/sizeof(char)];
    int i = 1;
    while ((read = getline(&line, &len, cptr)) != -1) {
        if (i==day) {
            char strtowrite[7/sizeof(char) + strlen(event)/sizeof(char)];
            sprintf(strtowrite, "%d - %s\n", i, event);
            strcat(dates, strtowrite);
        }
        else {
            strcat(dates, line);
        }
        i += 1;
    }
    printf("%s", dates);
    fclose(cptr);
    cptr = fopen(filename, "w");
    fprintf(cptr, "%s", dates);
    fclose(cptr);
}

int main() {
    createCalendar("january");
    addToDay("january", 12, "event");
}

and the first line of output is: í¬_<89>lU1 - (in the file) output 的第一行是:í¬_<89>lU1 - (在文件中)

Try this尝试这个

char dates[177/sizeof(char) + strlen(event)/sizeof(char)] = {0};

in your addToDay function when declaring the dates variable.在声明日期变量时,在您的 addToDay function 中。 I think that you do not set the memory there, so there might be some junk in that memory location.我认为您没有在那里设置 memory,因此该 memory 位置可能存在一些垃圾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM