[英]C Programming. Program crashing when trying to read and write
我現在很難解決這個問題...在我復制文件的功能之一中,嘗試從一個文件讀取到另一個文件時,它總是崩潰。 另外,我還是個初學者,對於我犯的任何錯誤,我們深表歉意。
int file_copy(void)
{
char path_new[MAX_PATH];
file_load();
printf("New name: ");
scanf("%s", path_new); // <---- Crash right after entering a new path
FILE *fr_source, *fw_target;
if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {
printf("Error while opening one of these files");
exit(6);
}
int c;
while((c = getc(fr_source)) != EOF) {
fputc(c, fw_target);
}
printf("File copied successfully.\n");
if ((fclose(path_current)) && (fclose(path_new)) == EOF) {
printf("Error while closing one of these files");
exit(7);
}
return 0;
}
int file_load(void)
{
printf("Path to current file: ");
scanf("%s", path_current);
if (file_access(path_current) != 0)
exit(2);
return 0;
}
int file_access(char path[])
{
if ((access(path, F_OK)) != 0) {
printf("ERROR = %s.\n", strerror(errno));
exit(1);
}
return 0;
}
編輯:現在,將這兩個分開后,它可以工作:
if ((fr_source = fopen(path_current, "r")) == NULL) {
printf("Error while opening one of these files");
exit(6);
}
if ((fw_target = fopen(path_new, "w")) == NULL) {
printf("Error while opening '%s'\n", path_new);
exit(6);
}
嘗試換線
if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {
至
if (((fr_source = fopen(path_current, "r")) == NULL) || ((fw_target = fopen(path_new, "w")) == NULL)) {
同樣的,
if ((fclose(path_current)) && (fclose(path_new)) == EOF) {
應該
if ((fclose(fr_source) == EOF) || (fclose(fw_target) == EOF)) {
使用格式(ptr1 && ptr2) == NULL
會造成混淆,並且會在許多編譯器上引發警告(當然,如果您使用gcc -Wall -pedantic
,我會這樣做)。
另外, int fclose(FILE*)
,將打開文件指針而不是字符串作為參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.