You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FindLineNumber.m 1.6KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function [ line ] = FindLineNumber( fid, fileSize, lineNum )
  2. %FindLineNumber Find a line number in file where each line starts with the
  3. %number
  4. % Detailed explanation goes here
  5. currPos = floor(fileSize / 2);
  6. minPos = 0;
  7. maxPos = fileSize;
  8. while(1)
  9. %fprintf('searching for %d, currPos %d, minPos %d, maxPos %d\n', lineNum, currPos, minPos, maxPos);
  10. res = fseek(fid, currPos, 'bof');
  11. line = fgetl(fid);
  12. if currPos > 0
  13. line = fgetl(fid);
  14. if line == -1
  15. fprintf('line == -1');
  16. currNode = -1;
  17. break;
  18. end
  19. end
  20. %split the line into a vector of node numbers
  21. r = str2double(regexp(line, ' ', 'split'));
  22. %r(2) = []; %the second number is a timestamp
  23. currNode = r(1); %the first number is the node and the following numbers are the neighbor indexes
  24. %if we are close to the node, start linear search
  25. if lineNum >= currNode && lineNum - currNode < 10
  26. while currNode < lineNum
  27. line = fgetl(fid);
  28. r = str2double(regexp(line, ' ', 'split'));
  29. currNode = r(1); %the first number is the node and the following numbers are the neighbor indexes
  30. end
  31. break;
  32. %otherwise continue with binary search
  33. else
  34. if currNode > lineNum
  35. maxPos = currPos;
  36. currPos = floor((currPos + minPos) / 2);
  37. else
  38. minPos = currPos;
  39. currPos = floor((currPos + maxPos) / 2);
  40. end
  41. end
  42. end
  43. %fprintf('searched for %d, found %d\n', lineNum, currNode);
  44. end