1

現在、fopen を使用してファイルを開くことができます (と思います)。テスト目的で、ファイルの内容を出力ファイルに渡せるようにしたいのですが、望ましい結果が得られません。ここにいくつかのコードがあります:

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

int main(int argc, char* argv[]){ //practice on utilizing IO
char filepath[100];
char filepath2[100];
strcpy(filepath,"./");
strcpy(filepath,"./");
char typed[90];
char msg[1024];
FILE * new_file;
FILE * old_file;

// printf("Input file to be created\n");
printf("File to be opened as input: \n");
printf("--->");

fgets(typed,90,stdin); //read in file name
strtok(typed, "\n");
strcat(filepath,typed);
old_file =  fopen(filepath, "r");

printf("file to output to: \n");
fgets(filepath2,100, stdin);  
strtok(filepath2, "\n");
///attempt to create that file
new_file = fopen(filepath2,"w");
//printf("%s\n", msg);

}

どんな助けでも大歓迎です。

4

2 に答える 2

1

あなたのファイルに似た小さな c ファイルを作成しました。C の i/o をよりよく理解するのに役立つことを願っています。

コード:

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

int main(int argc, char *argv[]) {

char fileNameOne[] = "test.txt";
char fileNameTwo[] = "new.txt";

FILE* oldFile;
FILE* newFile;

printf("The file being read from is: %s\n", fileNameOne);
//get a File pointer to the old file(file descriptor)
oldFile = fopen(fileNameOne, "r");

//get a File pointer to the new file(file descriptor)
//a+ is to open for read and writing and create if it doesnt exist
//if we did not specify a+, but w+ for writing, we would get an invalid file descriptor because the file does not exist
newFile = fopen(fileNameTwo, "a+");
if (newFile == 0) {
    printf("error opening file\n");
    exit(1);
}
//read everything from the old file into a buffer
char buffer[1024];

printf("Contents of old file:\n");
while (fread(buffer, 1, 1024, oldFile) != 0) {
    //if fread returns zero, and end of file has occured
     printf("%s", buffer);
     //directly write the contents of fileone to filetwo
     fwrite(buffer, 1, 1024, newFile);
}

printf("The file %s has been read and written to %s\n", fileNameOne, fileNameTwo);

printf("Verification: Contents of file two:\n");

//move the offset back to the beginning of the file
rewind(newFile);

while (fread(buffer, 1, 1024, newFile)!= 0) {
    printf("%s", buffer);
}

printf("\nEnd of file 2\n");
}

同じディレクトリに test というテキスト ファイルを作成し、そこにゴミを書き込んだだけです。これが出力です。

出力:

The file being read from is: test.txt
Contents of old file:
Hi, my name is Jack!

HAHAHAH

YOU DON"T even know!


The file test.txt has been read and written to new.txt
Verification: Contents of file two:
Hi, my name is Jack!

HAHAHAH

YOU DON"T even know!



End of file 2
于 2013-04-26T04:16:34.110 に答える