Understanding C String Concatenation

穿精又带淫゛_ 提交于 2019-12-12 02:48:15

问题


For an assesment in C i have to take two files with strings within them, and a string to concatenate them together e.g:

If file1 contains

Now is the

time for all

good men to

come to the aid of

the party.

and file2 contains:

alpha

beta

gamma

then the output from

scat XX file1 file2

(scat being the program name)

should be

Now is theXXalpha

time for allXXbeta

good men toXXgamma

come to the aid ofXX

the party.XX

and the output from

scat XX file2 file1

should be

alphaXXNow is the

betaXXtime for all

gammaXXgood men to

XXcome to the aid of

XXthe party.

In order to understand this i've been trying to play around with string concatenation trying to manually concat strings together.

My question is (A: how to i access individual lines of a file in c?) and B: if I manually input:

  char *str1 = "hello";

  char *str2 = "world";

how would i add these strings together without a predefined function. My thoughts initially were to use a for loop:

 for(str1; *str1 != '\0'; str1++)

     if(*str1 == '\0')

       *str1++ = *str2++;

my only issue is wouldn't this cause a seg fault due to memory access?

when i encounter a '\0' in a string..how can i extend this string? unless i just copy both strings into a new char str3[200] ?

(all of the above is to try and help me understand how strings and string concat works, any assistance in learning this would be appreciated.)

Euden


回答1:


Well, there is no need for string concatenation if the only goal is reading from two files, and writing to stdout, only a one-character buffer is sufficient, and a simple state machine will do.

#include <stdio.h>

int main (int argc, char **argv)
{
FILE *fp1, *fp2;
int ch, state ;

if (argc < 4) {
        fprintf(stderr, "Argc=%d, should be > 3\n", argc);
        return 0;
        }

for (state = 0; state < 42;     ) {
        switch (state) {
        case 0:
                fp1 = fopen (argv[2], "r"); if (!fp1) return 0;
                fp2 = fopen (argv[3], "r"); if (!fp2) { fclose (fp1); return 0;}
                state++;
        case 1:
                ch = fgetc(fp1);
                if (ch == EOF) state = 10;
                else if (ch == '\n') state =2;
                else putchar(ch);
                break;
        case 2:
                fputs( argv[1], stdout);
                state = 3;
        case 3:
                ch = fgetc(fp2);
                if (ch == EOF) state = 22;
                else if (ch == '\n') state =4;
                else putchar(ch);
                break;
        case 4:
                putchar(ch);
                state = 1;
                break;
        case 10: /* fp1 exhausted */
                ch = fgetc(fp2);
                if (ch == EOF) state = 30;
                else if (ch == '\n') state = 12;
                else {
                        fputs( argv[1], stdout );
                        putchar(ch);
                        state = 11;
                        }
                break;
        case 11:
                ch = fgetc(fp2);
                if (ch == EOF) state = 13;
                else if (ch == '\n') state = 12;
                else putchar(ch);
                break;
        case 12:
                putchar(ch);
                state = 10;
                break;
        case 13:
                putchar('\n');
                state = 30;
                break;
        case 20: /* fp2 exhausted */
                ch = fgetc(fp1);
                if (ch == EOF) state = 30;
                else if (ch == '\n') state = 21;
                else putchar(ch);
                break;
        case 21:
                fputs( argv[1], stdout);
                state = 22;
        case 22:
                putchar('\n');
                state = 20;
                break;
        case 30: /* both fp1+fp2 exhausted */

                fclose (fp1);
                fclose (fp2);
                state = 42;
                }
        }
return 0;
}

Disclaimer: don't try this at home.




回答2:


I'm not going to do it for you, but here are some tips/pitfalls.

  1. Handle corner cases. What if the files don't have the same number of lines?

  2. Unless you really have to support unlimited lines (ask your professor) I would suggest a buffer of 2048 characters for the input and 5000 for the output (2*2048 + concatenation string).

  3. You'll want to read using fgets into the input buffers for both files, and then concatenate them with strncat.




回答3:


How you go about reading the lines from your input files should probably be based on what functions your professor has taught you or had you read about. Certainly not the best way to do it, but a simple way is to use fopen() to open the file, then getline() to read each line. This is simple but requires you to allocate excess buffer space (and risk a buffer overrun if you're not sure how much space you'll need). It also requires you to trim the \n from each line of input.

As to concatenating without using the built-in function, your proposed method may have the problem you fear. You need to know how much space you have available to write into and if you go beyond that, you're asking for trouble (and you will receive it). Creating a new buffer for the purpose of placing the output will keep you safe, but you suggest creating two new buffers; only one is needed.




回答4:


If you need hints, review the source code behind Martin Broadhurst's Reading a Text File in C and the function strcat(). There are many places on the internet where source code for strcat() is available.



来源:https://stackoverflow.com/questions/9555167/understanding-c-string-concatenation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!