为什么输出字符串显示我从未写过的数据?

aga*_*row 1 c output

我正在编写一个程序,通过向每个字符添加10来加密文件.不知何故,一部分程序工作目录正在打印到文件中,我不明白为什么.

#include <stdio.h>
    int main(void){
        FILE *fp;
        fp=fopen("tester.csv","r+");
        Encrypt(fp);      
        fclose(fp);
    }

    int Encrypt(FILE *fp){
        int offset=10;
        Shift(fp, offset);
    }
    int Decrypt(FILE *fp){
        int offset= -10;
        Shift(fp, offset);
    }
    int Shift(FILE *fp, int offset){
        char line[50],tmp[50], character;
        long position;
        int i;
        position = ftell(fp);
        while(fgets(line,50,fp) != NULL){
            for(i=0;i<50;i++){
                character = line[i];
                character = (offset+character)%256;
                tmp[i] = character; 
                if(character=='\n' || character == 0){break;}                
            }
            fseek(fp,position,SEEK_SET);
            fputs(tmp,fp);
            position = ftell(fp);
            fseek(stdin,0,SEEK_END);
        }
      }
Run Code Online (Sandbox Code Playgroud)

该文件最初读取

this, is, a, test
i, hope, it, works!
Run Code Online (Sandbox Code Playgroud)

程序运行后:

~rs}6*s}6*k6*~o}~
/alexio/D~6*y|u}+
k6*~o}~
/alexio/D
Run Code Online (Sandbox Code Playgroud)

users/alexio/Desktop是路径的一部分.这是怎么发生的?

Kar*_*ath 5

因为你"编码"字符串,它不会被空终止(这是你的情况),或者它甚至在字符串结尾之前包含一个null(字符+偏移量%256 == 0).稍后您尝试将其写为字符串,它会超出您的缓冲区,并输出您的部分程序参数.

使用freadfwrite.