fwrite破坏了我的文本文件

时间:2015-01-26 16:38:58

标签: c fwrite fread

我已经为我的一类课程修补了几天,我不能得到合作。我曾尝试查看fread和fwrite的在线资源,查看我教授的例子,并一次又一次地尝试解决这个问题,但没有任何效果。无论我做什么,fwrite都会让我的文本编辑器无法检测到任何类型的字符编码,因此我假设fwrite要么将内存地址或垃圾值写入文件,要么让我能够'读它。该程序只是将一个文件的内容写入另一个文件。

这是我的代码。

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

int main(int argc, char* argv[]) {
//initialize files
FILE* infile,  *outfile;
char* buffer;
int read = 0;

//handle the case of having the wrong number of inputs.
if (argc != 4){

    printf("Error: incorrect number of inputs\n");
    //returning 1 will tell us that this was an error (as opposed to returning zero)
    return 1;
}
else{
    //handle the case of not having read acces to file 1
    if ( access(argv[1], R_OK) == 1){

        printf("Error: you do not have read access to the first file\n");
        return 1;
    }
    else {
        //handle the case of not having write access to file 2
        if ( access(argv[2], W_OK) == 1){
            printf("Error: you do not have write access to the second file\n");
            return 1;
        }
        else{
            //handle a bad  buffer size (zero or negative number)
            if ((int)*argv[3] < 0){
                printf("Error: bad input for buffer size.\nBuffer size: %d \n", (int)*argv[3]);
                return 1;
            }
        }
    }
    //open the files in the correct mode.
    infile = fopen(argv[1], "r");
    outfile = fopen(argv[2], "w");


    buffer = malloc((int)*argv[3]);

    while (!feof(infile)){
        read = fread (buffer,1,(int)*argv[3],infile);
        fwrite(buffer,1,(int)*argv[3],outfile);
    }

}
//close files, and deallocate the buffer.
fclose(infile);
fclose(outfile);
free(buffer);
//if we made it here, then that means that our program ran correctly, so return zero.
return 0;
}

2 个答案:

答案 0 :(得分:2)

这是错误的

(int)*argv[3]

将其更改为

atoi(argv[3])

并且如果将值存储在某个地方会更好,并检查它是否可以转换为整数,类似于

int size;
char *endptr;

size = strtol(argv[3], &endptr, 10);
if (*endptr != '\0')
    errorNotAnIntegerAbortHere();
buffer = malloc(size);
.
. 
.

不是这样,*argv[3]等同于argv[3][0],它只是argv[3]中的第一个字符。

答案 1 :(得分:1)

fread将返回少于no。 EOF请求的字节数。

更改为

if (read)
    fwrite(buffer,1,read,outfile);