Beispiel #1
0
        public static P5Scalar Open3Args(Runtime runtime, P5Scalar target, string open_mode, P5Scalar value)
        {
            FileMode mode;
            FileAccess access;
            bool is_read = false, is_write = false, truncate = false;

            switch (open_mode)
            {
            case ">":
                mode = FileMode.OpenOrCreate;
                access = FileAccess.Write;
                is_write = truncate = true;
                break;
            case "<":
                mode = FileMode.Open;
                access = FileAccess.Read;
                is_read = true;
                break;
            case ">>":
                mode = FileMode.Append;
                access = FileAccess.Write;
                is_write = true;
                break;
            case "+>":
                mode = FileMode.OpenOrCreate;
                access = FileAccess.ReadWrite;
                is_read = is_write = truncate = true;
                break;
            case "+<":
                mode = FileMode.OpenOrCreate;
                access = FileAccess.ReadWrite;
                is_read = is_write = true;
                break;
            default:
                throw new P5Exception(runtime, string.Format("Unknown open() mode '{0}'", open_mode));
            }

            FileStream filestream;

            try
            {
                filestream = new FileStream(value.AsString(runtime), mode, access);
                if (truncate)
                    filestream.SetLength(0);
            }
            catch (IOException)
            {
                // TODO set $!
                return new P5Scalar(runtime, false);
            }

            // TODO handle encoding
            var handle = new P5Handle(
                runtime,
                is_read ? new StreamReader(filestream) : null,
                is_write ? new StreamWriter(filestream) : null);

            target.SetHandle(runtime, handle);

            return new P5Scalar(runtime, true);
        }