I need some help on deleting the last character in a txt file. For example, if my txt file contains 1234567, I need the C++ code to delete the last character so that the file becomes 123456. Thanks guys.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The only way to do this in portable code is to read in the data, and write out all but the last character.
If you don't mind non-portable code, most systems provide ways to truncate a file. The traditional Unix method is to seek to the place you want the file to end, and then do a write of 0 bytes to the file at that point. On Windows, you can use SetEndOfFile. Other systems will use different names and/or methods, but nearly all will have the capability in some form.
If the input file is not too large, you can do the following:-
If the file is too large, you can possibly use a temporary file instead of a character array. It will be a bit slow though.
For a portable solution, something along these lines should do the job:
Here's a more robust method, going off Alex Z's answer:
The trick is these lines, which allow you to read the entire file efficiently into the string, and not just a token:
This is inspired from Jerry Coffin's first solution in this post. It is supposed to be the fastest solution there.