在C-.TXT中编程加载、打印和保存



我需要一些关于此代码的帮助:

int main(int argc, char** argv)
{
    
    char text[500]; /* Create a character array that will store all of the text in the file */
    char line[100]; /* Create a character array to store each line individually */
    
    FILE *file; /* Create a pointer to the file which will be loaded, to allow access to it */
    char fileName[30]; /* Create a character array to store the name of the file the user want to load */
    
    printf("Enter the name of the file containing ship information: ");
    scanf("%s", fileName);
    
    /*Try to open the file specified by the user. Use error handling if file cannot be found*/
    file = fopen(fileName, "r"); /* Open the file specified by the user in 'read' mode*/
    if(file == NULL)
    {
        perror("The following error occurred: ");
        printf("Value of errno: %dn", errno);
    }
    else
    {
        printf("File loaded. "); /* Display a message to let the user know
                                  * that the file has been loaded properly */
    }
    while(fgets(line, 100, file)!="n")
    {
    }
    
    return 0;
    return (printf);
}

1) 我想要一个菜单,例如:[l]oad-[s]ave,当我写";L";然后我转到:

printf("Enter the name of the file containing ship information: ");
  1. 我需要帮助如何打印到txt文件,以及如何用另一个名字再次保存它。我的意思是我选择了这个名字

根据您的问题1,即菜单,1) 我想要一个菜单,例如:[l]oad-[s]ave,当我写"l"时,我会转到:

printf("输入包含船舶信息的文件名:");

对于该部分,char inpChar;

do {
    printf("enter menu: [l]oad - [s]aven");
    scanf("%c", &inpChar);
} while((inpChar != 'l') && (inpChar != 'L') && (inpChar != 's') && (inpChar != 'S'));
if((inpChar == '1') || (inpChar == 'L'))
{
     printf("Enter the name of the file containing ship information: ");
     scanf("%s", filename);
}

对于打印到文件的Q2,

file = fopen(filename, "a");
fprintf(file, "%s", line);
fclose(file);

我最近确实做了一个"文件en/解密器"。它不仅有一个相当不错的选项菜单,还处理文件处理。不是最好的评论,可能有点混乱,但我敢肯定,如果你读了它,你会发现它很有用,或者至少会得到一些操作。

我建议先阅读"man()"函数,或者用"./a.out-h"编译并运行它,以更容易地了解代码。

#include <stdio.h>
#include <stdlib.h>
/* ENCRYPTING FILES
  15.Dec.2012
  By Morten Lund */
#define ALPHA "\~!?=#)%(&[{]}|@,.;:-_*^+<>1234567890abcdefghijklmnopqrstuvwxyzABCDEFG HIJKLMNOPQRSTUVWXYZ/$"
#define CRYPT_ALPHA "/#UwVM{>12E+j,4amN&stin]Ao_6}Q|7q[!f(FJKcLBz^)XYdhZkl9e?Wv@u;35yHrg< P*pSGTx=Ib~%R0$O.8:-DC\"
#define ALPHA_SIZE sizeof(ALPHA)
void man();
void crypt(FILE *fpIN, FILE *fpOUT, char mode);
void replaceOriginal(char *inFileName, char *outFileName);
int main(int argc, char* argv[]) {
// Check if ALPHA and CRYPT_ALPHA is same size
if (sizeof(ALPHA) != sizeof(CRYPT_ALPHA)) {
    printf("ALPHA and CRYPT_ALPHA is not the same size!!");
    return EXIT_FAILURE;
}
/*------START-------OPTIONS MENU:-------START-----*/
char *inFileName;               // Input file name/dir
char *outFileName = "out.txt";  // Output file name/dir
char mode = 'N';                // E=encrypt, D=decrypt mode. N=Not set
int replaceMode = 0;            // Replace original file :default is OFF
int x;
for (x = 1; x < argc; x++) {
    if (strcmp(argv[x], "-e") == 0) {    // Encryption mode
        mode = 'E';
    }
    if (strcmp(argv[x], "-d") == 0) {    // Decryption mode
        mode = 'D';
    }
    if (strcmp(argv[x], "-r") == 0) {    // Replace original file
        replaceMode = 1;
    }
    if (strcmp(argv[x], "-f") == 0) {    // Input file option
        x++;
        inFileName = argv[x];
    }
    if (strcmp(argv[x], "-o") == 0) {    // Output file option
        x++;
        outFileName = argv[x];
    }
}
/*------END-------OPTIONS MENU:--------END-------*/
FILE *fpIN, *fpOUT; // Creating file pointer to in and output file
// Check if mode is set to E OR D. Check if input and output file is set.
if (mode == 'E' || mode == 'D' && inFileName != NULL && outFileName != NULL) {
    // If inFileName exists and is readable, it is opened, else return EXIT_FAILURE 
    if ((fpIN = fopen(inFileName, "r")) == NULL) {
        printf("nERROR! Input file: %snFile does not exist or is not readable!nn", inFileName);
        fclose(fpIN);
        return EXIT_FAILURE;
    }
    // Check if Output file allready exist.
    if ((fopen(outFileName, "r")) != NULL) {
        printf("nOutput file: %snFile allready exist, do you want to overwrite it? [Y/N]: ", outFileName);
        char choice;
        scanf("%c", &choice);
        while (choice == 'N' || choice == 'n')
            return EXIT_FAILURE;
    }
    // If outFileName is writeble, it is opened, else return EXIT_FAILURE
    if ((fpOUT = fopen(outFileName, "w")) == NULL) {
        printf("nERROR! Output file: %sn File or location is not writeble!nn", outFileName);

        fclose(fpIN);  // Closing input pointer
        fclose(fpOUT); // and output pointer
        return EXIT_FAILURE;
    }
    printf("nInput file: %sn", inFileName);
    printf("Output file: %sn", outFileName);
    printf("mode (E)ncryption (D)ecrypting: %cn", mode);
    crypt(fpIN, fpOUT, mode);
    fclose(fpIN);  // Closing input pointer
    fclose(fpOUT); // and output pointer
} else
    man();
// Check if set, and if, then replace original file
if (replaceMode)
    replaceOriginal(inFileName, outFileName);
return EXIT_SUCCESS;
}
void crypt(FILE *fpIN, FILE *fpOUT, char mode) {
char *alphaFrom, *alphaTo;      // Alphabet to copy from, to
if (mode == 'E') {               // If mode=Encrypt, copy from ALPHA to CRYPT_ALPHA
    alphaFrom = ALPHA;
    alphaTo = CRYPT_ALPHA;
}
else if (mode == 'D') {          // If mode=Decrypt, copy from CRYPT_ALPHA to ALPHA
    alphaFrom = CRYPT_ALPHA;
    alphaTo = ALPHA;
}
char curChar; int i;                        // Current character, and counter (i)
while ((curChar = fgetc(fpIN)) != EOF) {    // Assign curChar from fpIN as long it's not EOF
    for (i = 0; i < ALPHA_SIZE; i++) {      // For every character in alphabet size
        if (curChar == alphaFrom[i])        // If character = alphaFrom, replace with alphaTO
            fputc(alphaTo[i], fpOUT);
    }
    if (curChar == 'n')                    // Finding n and inserting with n
        fputc('n', fpOUT);
    if (curChar == 't')                    // Finding t and inserting with t
        fputc('t', fpOUT);
}
}
void replaceOriginal(char *inFileName, char *outFileName) {
    if (remove(inFileName) == 0) {                  // Remove inFileName
        if (rename(outFileName, inFileName) == 0)   // Rename outFileName
            printf("File %s successfully replacedn", inFileName);
    } else
        printf("Couldn't delete %s.. Replace failed", inFileName);
}
void man() {
printf("n.....Simple Crypter.....nnUsage: sCrypter [Arguments] -f [input file]ntOr: sCrypter -e -f file.txtntOr: sCrypter -d -r -f file.txtntOr: sCrypter -e -f file.txt -o file2.txtnn");
printf("  [-h]  This page.n");
printf("  [-f]  Set input file.n");
printf("  [-o]  Set output file [OPTIONAL] default: out.txt.n");
printf("  [-e]  Encrypting input file.n");
printf("  [-d]  Decrypting input file.n");
printf("  [-r]  Replace the input file with the new output file.nn");
printf("Warning! If [-r] is used, out.txt will be used as tmp file.n");
printf("[-o] can be used in combination with [-r] to insure that another tmp file is used.nn");
}

抱歉我英语不好。

最新更新