read.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2013 Unknown
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package zip
  15. import (
  16. "archive/zip"
  17. "os"
  18. "strings"
  19. )
  20. // OpenFile is the generalized open call; most users will use Open
  21. // instead. It opens the named zip file with specified flag
  22. // (O_RDONLY etc.) if applicable. If successful,
  23. // methods on the returned ZipArchive can be used for I/O.
  24. // If there is an error, it will be of type *PathError.
  25. func (z *ZipArchive) Open(name string, flag int, perm os.FileMode) error {
  26. // Create a new archive if it's specified and not exist.
  27. if flag&os.O_CREATE != 0 {
  28. f, err := os.Create(name)
  29. if err != nil {
  30. return err
  31. }
  32. zw := zip.NewWriter(f)
  33. if err = zw.Close(); err != nil {
  34. return err
  35. }
  36. }
  37. rc, err := zip.OpenReader(name)
  38. if err != nil {
  39. return err
  40. }
  41. z.ReadCloser = rc
  42. z.FileName = name
  43. z.Comment = rc.Comment
  44. z.NumFiles = len(rc.File)
  45. z.Flag = flag
  46. z.Permission = perm
  47. z.isHasChanged = false
  48. z.files = make([]*File, z.NumFiles)
  49. for i, f := range rc.File {
  50. z.files[i] = &File{}
  51. z.files[i].FileHeader, err = zip.FileInfoHeader(f.FileInfo())
  52. if err != nil {
  53. return err
  54. }
  55. z.files[i].Name = strings.Replace(f.Name, "\\", "/", -1)
  56. if f.FileInfo().IsDir() && !strings.HasSuffix(z.files[i].Name, "/") {
  57. z.files[i].Name += "/"
  58. }
  59. }
  60. return nil
  61. }