Home | History | Annotate | Download | only in native
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include "LocalArray.h"
     18 #include "readlink.h"
     19 
     20 #include <string>
     21 #include <unistd.h>
     22 
     23 bool readlink(const char* path, std::string& result) {
     24     // We can't know how big a buffer readlink(2) will need, so we need to
     25     // loop until it says "that fit".
     26     size_t bufSize = 512;
     27     while (true) {
     28         LocalArray<512> buf(bufSize);
     29         ssize_t len = readlink(path, &buf[0], buf.size());
     30         if (len == -1) {
     31             // An error occurred.
     32             return false;
     33         }
     34         if (static_cast<size_t>(len) < buf.size()) {
     35             // The buffer was big enough.
     36             result.assign(&buf[0], len);
     37             return true;
     38         }
     39         // Try again with a bigger buffer.
     40         bufSize *= 2;
     41     }
     42 }
     43