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
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.
Disclaimer: don’t try this at home.