简体   繁体   English

如何通过命令行参数传递参数来将文本替换到文件的特定位置

[英]How to replace the text into a particular location of a file by passing the argument via command line argument

My intention is to read the second element in the 1st row and replace it with the value which we pass as an command line argument and replace it in the input.txt file 我的意图是读取第一行中的第二个元素,并将其替换为我们作为命令行参数传递的值,并将其替换为input.txt文件

Input file:logic.txt 输入文件:logic.txt

one=1234 一个= 1234

two=3456 两个= 3456

I want my file to be changed like this after compiling the code. 我希望在编译代码后像这样更改我的文件。

./a.out 1567 ./a.out 1567

Currently i am getting output like this 目前我正在得到这样的输出

./filelogic 1567 ./filelogic 1567

1567=1234 1567 = 1234

two=5678 两个= 5678

Expected Output file should be modified like this after the compilation 预期的输出文件在编译后应该像这样修改

logic.txt 逻辑文件

one=1567 一个= 1567

two=5678 两个= 5678

        char buf[MAXSIZE] = {};
        int num = 0;
        int i = 0;

        num = atoi(argv[1]);

        printf("%d",num);

       FILE *fp1;
              fp1 = fopen("logic.txt","r");//currently reading the file.
       if(fp1 != NULL)
       {

                 fseek(fp1,3,0);//Need to Move the pointer to the 3rd position where i need to replace the num(fseek(fp1,??,0))-->how we can achieve that.

                 //Using which method i can replace the num value into a file (means need to replace 1234 inplace of 1567)

               //Once the changes are done need to replace in the same file.

                fread(buf, 1, MAXSIZE, fp1);

                printf("%s\n",buf);

                 fclose(fp1);


       }else {
                printf("Cannot open file"");
                    exit(1);
       }

Could someone guide me to resolve this issue?Thanks in advance 有人可以指导我解决此问题吗?

You can make replacements to a file in-place , but you should not do this in practice. 可以 就地替换文件,但实际上不应该这样做。 You will likely corrupt the file if you attempt to replace characters and do not make an exact one-to-one replacement of characters already in the file. 如果尝试替换字符并且不对文件中已有的字符进行精确的一对一替换,则很可能损坏文件。

To safely change the contents of a file, read the entire file contents into memory, make the changes needed, and then truncate the current file and write the new contents to the truncated file. 为了安全地更改文件的内容,请将整个文件的内容读取到内存中,进行所需的更改,然后截断当前文件并将新内容写入截断的文件。 (if the file is too large for in-memory operations, then use a temporary file) (如果该文件太大,无法进行内存中操作,请使用一个临时文件)

You do not want to use atoi to convert the string "1567" to an integer. 您不想使用atoi将字符串"1567"转换为整数。 You are replacing characters in a file, not integer values in a binary file, so work with characters instead. 你是在一个文件中的二进制文件替换字符 ,而不是整数值,所以用文字工作,而不是。

Your project is complicated by only wanting to replace the text after the first '=' sign. 您的项目很复杂,只希望替换第一个'='符号之后的文本。 This may or may not be on the first line of the file, so you will need some flag to indicate when the first '=' is found and the replacement is made. 它可能位于文件的第一行,也可能不在文件的第一行,因此您将需要一些标志来指示何时找到第一个'='并进行替换。 (once the replacement is made, you can simply break your read loop and close the file -- but below the example output all lines for convenience) (一旦替换完成,您可以简单地中断读取循环并关闭文件-但为方便起见,在示例下面输出所有行)

Any time you close a file after writing to it, you should validate the return of fclose to catch any stream errors, or errors that occurred on the last write that will not be apparent until the next file operation. 每次在写入文件后关闭文件时,都应验证fclose返回 ,以捕获任何流错误,或上一次写入时发生的错误,直到下一个文件操作时才发现。

With those cautions and caveats in mind, you could do something similar to: 考虑到这些警告和注意事项,您可以执行以下操作:

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

#define MAXSIZE 64          /* max line/buffer size */
#define FNAME "logic.txt"   /* default file name */
#define REPLACE "1567"      /* default replacement text */

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

    char buf[MAXSIZE] = "";         /* line buffer */
    const char *str = argc > 1 ? argv[1] : REPLACE; /* replacement string */
    int replaced = 0;               /* flag indicating replacement made */
    FILE *fp = fopen (FNAME, "r+"); /* open file reading/writing */

    if (!fp) {  /* validate file open for reading/writing */
        perror ("fopen-FNAME");
        return 1;
    }

    while (fgets (buf, MAXSIZE, fp)) {  /* read each line in file */
        if (!replaced) {                /* if replacement not yet made */
            char *p = strchr (buf, '=');    /* search for '=' in line */
            if (p) {                        /* if found */
                size_t plen = 0;            /* var for length to end */
                p++;                        /* advance past '=' sign */
                plen = strlen (p);          /* get length to end  */

                if (plen < strlen (str)) {  /* check avail length */
                    fprintf (stderr, "error: not enough space in line.\n");
                    return 1;
                }
                strcpy (p, str);                    /* copy str to p */
                if (fseek (fp, -plen, SEEK_CUR)) {  /* backup plen chars */
                    perror ("fseek(fp)");
                    return 1;
                }
                fputs (p, fp);  /* overwite contents with replacement */
                replaced = 1;   /* set flag indicating replacement   */
            }                   /* (you can break, and remove output */
        }                       /*  here if not writing to stdout)   */
        fputs (buf, stdout);    /* output lines to stdout (optional) */
    }
    if (fclose (fp) == EOF)     /* always validate close-after-write */
        perror ("fclose-FNAME");

    return 0;
}

Using your file logic.txt as an example input, and naming the executable filelogic as you have, the use and operation of the code above yields: 使用文件logic.txt作为示例输入,并根据需要命名可执行文件filelogic ,以上代码的使用和操作将产生:

logic.txt File Before logic.txt文件之前

$ cat logic.txt
one=1234

two=3456

Example Use/Output 使用/输出示例

$ ./filelogic
one=1567

two=3456

logic.txt File After 逻辑文件之后

$ cat logic.txt
one=1567

two=3456

Again, this is fine for a learning endeavor, but in practice, avoid making changes to files in-place as the risk of inadvertent file corruption far outweighs writing a new file with the changes. 再次,这对于学习非常有用,但是在实践中,请避免对文件进行就地更改,因为无意中文件损坏的风险远远大于使用更改编写新文件的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM