1

Hi i am trying to figure out how to copy only part of a line being read from a text file. I want to copy a line from a file called fileLine to a variable called line. The problem is, is that i only want to copy starting at index 10 in fileLine but memcpy dislikes that. How can i change this to make memcpy happy?

int stringLength = 0;
stringLength = strlen(fileLine);
memcpy(line, fileLine[10], stringLength); //this is where things go wrong.
5
  • "but memcpy dislikes that." what does this mean? Commented Dec 6, 2016 at 3:35
  • fileLine is the name of the file? Then strlen(fileLine) is the length of the name of the file. I don't think that's what you want... Commented Dec 6, 2016 at 3:36
  • memcpy(line, &fileLine[10], stringLength-10); Commented Dec 6, 2016 at 3:36
  • 1
    You (a) take the address of the 11th element, and (b) use strcpy() so you don't risk running off the end of the string: strcpy(line, &fileLine[10]); - or use stringLength = strlen(fileLine) - 10; if you insist on memcpy(). Commented Dec 6, 2016 at 3:37
  • YES! Thank you so much. I feel a little ridiculous that i didn't know that. Commented Dec 6, 2016 at 3:38

2 Answers 2

3

You have passed in a char type to something that expected a const void*. This would have been okay if you had passed it a char*. You can do that as either &fileLine[10] or fileLine + 10.

Since you are offsetting by 10, you also want to ensure you copy 10 fewer characters:

memcpy(line, &fileLine[10], stringLength-10);

Although you probably want to copy the string terminator too...

memcpy(line, &fileLine[10], stringLength-9);

Yuck!

Instead, you could use strcpy:

strcpy(line, fileLine + 10);

In all cases, make sure that line is an array or a pointer to memory that is actually allocated to your process.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use getline function to get part of the string. But first, you have to move your read pointer to the position from which you want to read using seekg function. seekg(ios flag, bytes); cin.getline(source, number of characters, ending character);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.