NoClPls
NoClPls

Reputation: 1

How to fill a string (which is in a struct) with null terminators?

Here is the task (it is translated so there may be some mistakes):

The default input file is a.bin, in which record-type structures are saved one after the other in binary (unformatted) format with no spaces in between. The record type is defined by

typedef struct {
    int id;
    char data [1024];
    long link;
} record;

The link element contains the sequence number of bytes at which another record in the same file begins. Since there is no space between records, the link should be a multiple of sizeof (record).

In the input file a.bin there are "wrong" records in the sense that they contain link elements that are not multiples of sizeof (record) and there are records where 0 ≤ link < (file length) is not valid. The task is to fill the data field completely with '\0' bytes in the wrong records, which is marked with the letter X in the example.

For example (assuming sizeof(record)==1040) if the input file contains (binary-unformatted):

About "123AB" 1040
1 "123xx" 3120
2 "1xxxB" 1041
3 "12xxxyy" 10400
5 "abcde" 0

output, after executing the program, should contain

0 "123AB" 1040
1 "123xx" 3120
2 X 1041
3 X 10400
5 "abcde" 0

where X is the tag for the 1024 byte string '\0'. (Quotes, spaces, etc. are added for clarity and are not in the actual input/output.)

I tried using strcpy and strcat to append the null terminators to the string, but that doesn't work since I cannot append something to a string defined in a struct. Does anyone have a clue on how to do this? I have written everything in my code up to the moment to add the nulls.

Upvotes: 0

Views: 123

Answers (1)

0___________
0___________

Reputation: 67835

To make a string empty it is not necessary to fill it with zeroes. Setting the first character is enough.

record rdata;

rdata.data[0] = 0;

If you want to fill the whole array :

memset(rdata.data, 0, sizeof(rdata.data));

Upvotes: 1

Related Questions